ngOnInit
とngAfterViewInit
の違いを理解できません。Angular2のngOnInitとngAfterViewInitの違いは何ですか?
私はそれらの間の唯一の違いが@ViewChild
であることを発見しました。次のコードによれば、その中のelementRef.nativeElement
は同じです。
どのシーンを使用する必要がありますか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'));
}
}
あなたが_rendered_を言うとき、あなたはそれが画面に表示されます意味ですか? (またはスクリーンに表示されるようにレンダリングされる) –
DOMに追加されるとき。 'display:hidden'を設定するとレンダリングされますが、画面には表示されません。しかし、ブラウザdevtoolsを使ってDOMを調べると、マークアップを見ることができます。 –
"ビューメンバーがレンダリングされる前にアクセスできませんでした。" - したがって、 'ViewChild'(vc)が' onNgInit'で利用可能であることをどのように説明しますか? https://plnkr.co/edit/AzhRe6bjnuPLKJWEJGwp?p=preview、説明していただけますか? –