Angular2的ngOnInit和ngAfterViewInit有什么区别? [英] What's the difference between ngOnInit and ngAfterViewInit of Angular2?
问题描述
我无法理解ngOnInit
和ngAfterViewInit
之间的区别.
I can not understand what the difference between ngOnInit
and ngAfterViewInit
.
我发现它们之间的唯一区别是@ViewChild
.根据以下代码,它们中的elementRef.nativeElement
是相同的.
I found the only difference between them is @ViewChild
. According to the following code, the elementRef.nativeElement
in them are the same.
我们应该使用哪个场景ngAfterViewInit
?
What scene should we use ngAfterViewInit
?
@Component({
selector: 'my-child-view',
template: `
<div id="my-child-view-id">{{hero}}</div>
`
})
export class ChildViewComponent {
@Input() hero: string = 'Jack';
}
//////////////////////
@Component({
selector: 'after-view',
template: `
<div id="after-view-id">-- child view begins --</div>
<my-child-view [hero]="heroName"></my-child-view>
<div>-- child view ends --</div>`
+ `
<p *ngIf="comment" class="comment">
{{comment}}
</p>
`
})
export class AfterViewComponent implements AfterViewInit, OnInit {
private prevHero = '';
public heroName = 'Tom';
public comment = '';
// Query for a VIEW child of type `ChildViewComponent`
@ViewChild(ChildViewComponent) viewChild: ChildViewComponent;
constructor(private logger: LoggerService, private elementRef: ElementRef) {
}
ngOnInit(){
console.log('OnInit');
console.log(this.elementRef.nativeElement.querySelector('#my-child-view-id'));
console.log(this.elementRef.nativeElement.querySelector('#after-view-id'));
console.log(this.viewChild);
console.log(this.elementRef.nativeElement.querySelector('p'));
}
ngAfterViewInit() {
console.log('AfterViewInit');
console.log(this.elementRef.nativeElement.querySelector('#my-child-view-id'));
console.log(this.elementRef.nativeElement.querySelector('#after-view-id'));
console.log(this.viewChild);
console.log(this.elementRef.nativeElement.querySelector('p'));
}
}
推荐答案
ngOnInit()
在第一次调用ngOnChanges()
之后被调用.每次通过更改检测更新输入时都会调用ngOnChanges()
.
ngOnInit()
is called after ngOnChanges()
was called the first time. ngOnChanges()
is called every time inputs are updated by change detection.
ngAfterViewInit()
.这就是@ViewChild()
依赖它的原因.在呈现视图成员之前,您无法对其进行访问.
ngAfterViewInit()
is called after the view is initially rendered. This is why @ViewChild()
depends on it. You can't access view members before they are rendered.
这篇关于Angular2的ngOnInit和ngAfterViewInit有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!