Get element by id - Angular2 Get element by id - Angular2 angular angular

Get element by id - Angular2


if you want to set value than you can do the same in some function on click or on some event fire.

also you can get value using ViewChild using local variable like this

<input type='text' id='loginInput' #abc/>

and get value like this

this.abc.nativeElement.value

here is working example

Update

okay got it , you have to use ngAfterViewInit method of angualr2 for the same like this

ngAfterViewInit(){    document.getElementById('loginInput').value = '123344565';  }

ngAfterViewInit will not throw any error because it will render after template loading


(<HTMLInputElement>document.getElementById('loginInput')).value = '123';

Angular cannot take HTML elements directly thereby you need to specify the element type by binding the above generic to it.

UPDATE::

This can also be done using ViewChild with #localvariable as shown here, as mentioned in here

<textarea  #someVar  id="tasknote"                  name="tasknote"                  [(ngModel)]="taskNote"                  placeholder="{{ notePlaceholder }}"                  style="background-color: pink"                  (blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }} </textarea>

import {ElementRef,Renderer2} from '@angular/core';@ViewChild('someVar') el:ElementRef;constructor(private rd: Renderer2) {}ngAfterViewInit() {      console.log(this.rd);       this.el.nativeElement.focus();      //<<<=====same as oldest way}


A different approach, i.e: You could just do it 'the Angular way' and use ngModel and skip document.getElementById('loginInput').value = '123'; altogether. Instead:

<input type="text" [(ngModel)]="username"/><input type="text" [(ngModel)]="password"/>

and in your component you give these values:

username: 'whatever'password: 'whatever'

this will preset the username and password upon navigating to page.