Angular 2.x selecting DOM element

后端 未结 5 863
隐瞒了意图╮
隐瞒了意图╮ 2020-12-30 01:06

I know it should be easy but angular 2.0 has no many examples yet..

In one of my components in some case I need to add class on my body tag. But my application is bo

5条回答
  •  囚心锁ツ
    2020-12-30 01:29

    DOM Manipulation in Angular 2 / 4 app

    To manipulate the DOM in Angular 2/4 apps, we need to implement the method ngAfterViewInit() of AfterViewInit. The method ngAfterViewInit() is called when the bindings of the children directives have been checked for the first time. In other words, when the view is initially rendered.

    The @ViewChild provides access to nativeElement. It is recommended to not access nativeElement inside the ngAfterViewInit() because it is not browser safe. Also, it's not supported by web workers. Web workers will never know when the DOM updates.

    The right way is to use renderer. The renderer needs to be injected to the component constructor. We need to provide an id reference to the HTML element on the view something like this:

    It shall be accessed by the corresponding coponent .ts file, something like this:

    
    export class SampleComponent implements AfterViewInit {
    
      @ViewChild("p1") p1;
    
      constructor(private renderer: Renderer2) //Renderer set to be depreciated soon
      { }
    
      ngAfterViewInit() {
    
        //recommended DOM manipulation approach
        this.renderer.setStyle(this.p1.nativeElement, //setElementStyle for soon to be depreciate Renderer
          'color',
          'red');
    
        //not recommended DOM manipulation approach
        //this.p1.nativeElement.style = "color:blue;";
      }
    
    }
    

提交回复
热议问题