What's the difference between ngOnInit and ngAfterViewInit of Angular2?

前端 未结 3 599
失恋的感觉
失恋的感觉 2021-01-30 09:55

I can not understand what the difference between ngOnInit and ngAfterViewInit.

I found the only difference between them is @ViewChild

3条回答
  •  天涯浪人
    2021-01-30 10:40

    Content is what is passed as children. View is the template of the current component.

    The view is initialized before the content and ngAfterViewInit() is therefore called before ngAfterContentInit().

    ** ngAfterViewInit() is called when the bindings of the children directives (or components) have been checked for the first time. Hence its perfect for accessing and manipulating DOM with Angular 2 components. As @Günter Zöchbauer mentioned before is correct @ViewChild() hence runs fine inside it.

    Example:

    @Component({
        selector: 'widget-three',
        template: ``
    })
    export class WidgetThree{
        @ViewChild('input1') input1;
    
        constructor(private renderer:Renderer){}
    
        ngAfterViewInit(){
            this.renderer.invokeElementMethod(
                this.input1.nativeElement,
                'focus',
                []
            )
        }
    }
    

提交回复
热议问题