Tôi không thể hiểu sự khác biệt giữa ngOnInit
và ngAfterViewInit
.Sự khác nhau giữa ngOnInit và ngAfterViewInit của Angular2 là gì?
Tôi thấy sự khác biệt duy nhất giữa chúng là @ViewChild
. Theo các mã sau, các elementRef.nativeElement
trong họ là như nhau.
Cảnh nào chúng ta nên sử dụng 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'));
}
}
Khi bạn nói _rendered_, làm bạn có nghĩa là nó sẽ xuất hiện trên màn hình? (hoặc được gửi để hiển thị trên màn hình) –
Khi được thêm vào DOM. Nếu bạn đặt 'display: hidden' cho đến khi hiển thị, nhưng không hiển thị trên màn hình. Nhưng nếu bạn điều tra DOM bằng cách sử dụng trình khám phá của trình duyệt, bạn sẽ có thể thấy đánh dấu. –
"_bạn không thể truy cập thành viên xem trước khi chúng được hiển thị_" - Vậy làm cách nào bạn giải thích rằng 'ViewChild' (vc) có sẵn trên' onNgInit'? https://plnkr.co/edit/AzhRe6bjnuPLKJWEJGwp?p=preview, Bạn có thể giải thích? –