在Angular 5中等待子组件初始化

时间:2018-10-27 15:43:33

标签: angular typescript

export class OrderDetailComponent implements OnInit {
	isOpenReviewPDF: boolean;
	@ViewChild(forwardRef(() => OrderReviewPdfComponent)) orderReviewPdfComponent: OrderReviewPdfComponent;
	
	ngOnInit() {
	}
	
	pulic exportPdf() {
		this.isOpenReviewPDF = true;
		if (this.orderReviewPdfComponent.isViewInit) {
            // How can I wait this code
			doSomething();
		}
	}
}


export class OrderReviewPdfComponent implements OnInit, AfterViewChecked {
	public isViewInit = false;
	
	ngOnInit() {
	}
	
	ngAfterViewChecked() {
		this.isViewInit = true;
	}
}
 <div *ngIf="isOpenReviewPDF">
	<order-review-pdf [commissionIncentive]="commissionIncentive"
		[orderEntry]="orderEntry" [siteSurvey]='siteSurvey'></order-review-pdf>
</div>

我在父组件上具有exportPdf()函数。我如何等待此条件(if(this.orderReviewPdfComponent.isViewInit))为true以运行doSomething()函数?目前,doSomething()永远不会调用。

1 个答案:

答案 0 :(得分:3)

如果要确保OrderReviewPdfComponent(子)模板已初始化,可以使用AfterViewInit内的OrderDetailComponent生命周期挂钩

ngAfterViewInit是在组件的模板及其子模板初始化时在其上调用的。因此,您应该在exportPdf()的{​​{1}}方法中调用ngAfterViewInit,就可以了。

OrderDetailComponent

现在,如果您想在export class OrderDetailComponent implements OnInit { ngOnInit() {} ngAfterViewInit() { // You can be sure that the template of OrderDetailComponent // and any of its child components was initialized in here. this.exportPdf(); } pulic exportPdf() { doSomething(); } } 中每次发生更改时都在exportPdf中调用OrderDetailComponent,那么您可以在{{1 }},其类型为OrderReviewPdfComponent。然后,您可以在每次更改时在其上调用@Output方法:

OrderReviewPdfComponent

现在,在EventEmitter的模板中,您可以通过执行emit绑定到import { ..., Output, ... } from '@angular/core'; export class OrderReviewPdfComponent implements OnInit, AfterViewChecked { @Output() somethingChanged: EventEmitter<any> = new EventEmitter<any>(null); ngOnInit() {} ngAfterViewChecked() { // This will inform OrderDetailComponent that OrderReviewPdfComponent // has initialized this.somethingChanged.emit(); } ... // Also whenever something changes, just call `this.somethingChanged.emit();` } 。试试这个:

OrderDetailComponent

这样,您将不需要在somethingChanged中使用(somethingChanged)="exportPdf()"布尔属性