Get element by id - Angular2

后端 未结 4 1218
一整个雨季
一整个雨季 2020-12-29 18:31

I have a code:

document.getElementById(\'loginInput\').value = \'123\';

But while compiling the code I receive following error:

4条回答
  •  独厮守ぢ
    2020-12-29 19:08

    (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

    
    

    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
    }
    

提交回复
热议问题