document.getElementById replacement in angular4 / typescript?

后端 未结 5 756
刺人心
刺人心 2020-11-29 03:10

So, im working with angular4 in my practice work and this is new for me. Luckyly, in order to get html elements and its values i used documen

相关标签:
5条回答
  • 2020-11-29 03:35

    You can tag your DOM element using #someTag, then get it with @ViewChild('someTag').

    See complete example:

    import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core';
    
    @Component({
        selector: 'app',
        template: `
            <div #myDiv>Some text</div>
        `,
    })
    export class AppComponent implements AfterViewInit {
        @ViewChild('myDiv') myDiv: ElementRef;
    
        ngAfterViewInit() {
            console.log(this.myDiv.nativeElement.innerHTML);
        }
    }
    

    console.log will print Some text.

    0 讨论(0)
  • 2020-11-29 03:40

    You can just inject the DOCUMENT token into the constructor and use the same functions on it

    import { Inject }  from '@angular/core';
    import { DOCUMENT } from '@angular/common'; 
    
    @Component({...})
    export class AppCmp {
       constructor(@Inject(DOCUMENT) document) {
          document.getElementById('el');
       }
    }
    

    Or if the element you want to get is in that component, you can use template references.

    0 讨论(0)
  • 2020-11-29 03:44

    Try this:

    TypeScript file code:

    (<HTMLInputElement>document.getElementById("name")).value

    HTML code:

     <input id="name" type="text" #name /> 
    0 讨论(0)
  • 2020-11-29 03:52
      element: HTMLElement;
    
      constructor() {}
    
      fakeClick(){
        this.element = document.getElementById('ButtonX') as HTMLElement;
        this.element.click();
      }
    
    0 讨论(0)
  • 2020-11-29 03:59

    For Angular 8 or posterior @ViewChild have an additional parameter called opts, which have two properties: read and static, read is optional. You can use it like so:

    // ...
    @ViewChild('mydiv', { static: false }) public mydiv: ElementRef;
    
    constructor() {
    // ...
    
    <div #mydiv></div>
    

    NOTE: Static: false is not required anymore in Angular 9. (just { static: true } when you are going to use that variable inside ngOnInit)

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