Get element by id - Angular2

后端 未结 4 1203
一整个雨季
一整个雨季 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:06

    Complate Angular Way ( Set/Get value by Id ):

    // In Html tag

     <button (click) ="setValue()">Set Value</button>
     <input type="text"  #userNameId />
    

    // In component .ts File

        export class testUserClass {
           @ViewChild('userNameId') userNameId: ElementRef;
    
          ngAfterViewInit(){
             console.log(this.userNameId.nativeElement.value );
           }
    
          setValue(){
            this.userNameId.nativeElement.value = "Sample user Name";
          }
    
    
    
       }
    
    0 讨论(0)
  • 2020-12-29 19:07

    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.

    0 讨论(0)
  • 2020-12-29 19:08
    (<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
    }
    

    0 讨论(0)
  • 2020-12-29 19:13

    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

    0 讨论(0)
提交回复
热议问题