How to select an element of the DOM for its id in ionic2

0

I have an element in DOM that is as follows:

<input type="text" id="miElemento" class="miElemento">
<ion-item class="input_float">
    <ion-label floating >Nombre:</ion-label>
    <ion-input class="x" id="nombre" #nombre name="nombre" type="text" [(ngModel)]="nombre" 
        (click)=" placeholderNombre=' Ej: Carlos Alberto Rodriguez Gacha';" 
        (blur)=" placeholderNombre=''" placeholder="{{placeholderNombre}}">
    </ion-input>
</ion-item>

and in my file I try to select it through method getElementById() in the following way:

console.log("resultado por id:",document.getElementById("miElemento"));
console.log("resultado por class:",document.getElementsByClassName("miElemento"));

The result by console is the following:

resultado por id: null
resultado por class: []length: 1 
                      miinput: div#nombre.miinput
                            0: div#nombre.miinput
                    __proto__: HTMLCollection

Why can not I do it with the getElementById() method?

    
asked by Daniel Enrique Rodriguez Caste 17.08.2017 в 22:19
source

1 answer

0

Angular can not take HTML elements directly so you need to specify the type of linked element.

You can use @ViewChild :

  

@ViewChild - is used on a property of the class that represents a component, allows to obtain the instances of native elements, directives and components that are in the template of the same.

1. We first add decorator #miElemento :

<div id="miElemento" #miElemento class="miElemento"> mi elemento </div>

2. In the component we add correspondence:

import { ElementRef, ViewChild, AfterViewInit } from '@angular/core';

...

export class ExamplePage
{
   @ViewChild( 'miElemento' ) miElemento: ElementRef;

   constructor() {}       

   ngAfterViewInit() {

       console.log( this.miElemento); // ElementRef {nativeElement: div#miElemento.miElemento}
       console.log( this.miElemento.nativeElement.id ); // "miElemento"
   }

...

View Demo

    
answered by 18.08.2017 / 00:06
source