Reputation: 33
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>
I have exportPdf() function on parent component. How can I wait this condition ( if(this.orderReviewPdfComponent.isViewInit) ) is true to run doSomething() function? Currently doSomething() never call.
Upvotes: 3
Views: 9866
Reputation: 39432
If you want to make sure that the OrderReviewPdfComponent
(child) template is initialized, you can use the AfterViewInit
lifecycle hook inside the OrderDetailComponent
ngAfterViewInit
is called on a Component when it's template and templates of it's children are initialized. So you should be calling the exportPdf()
in the ngAfterViewInit
method of the OrderDetailComponent
and you should be just fine.
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();
}
}
Now if you want to call exportPdf
in your OrderDetailComponent
every time there's a change in your OrderReviewPdfComponent
, then you can create an @Output
property in your OrderReviewPdfComponent
which would be of type EventEmitter
. You can then call the emit
method on it everytime there's a change:
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();`
}
Now in the template of OrderDetailComponent
, you can bind to somethingChanged
by doing (somethingChanged)="exportPdf()"
. Try this:
<div>
<order-review-pdf
[commissionIncentive]="commissionIncentive"
[orderEntry]="orderEntry"
[siteSurvey]='siteSurvey'
(somethingChanged)="exportPdf()">
</order-review-pdf>
</div>
So this way, you won't be needing the isOpenReviewPDF
boolean property in your OrderDetailComponent
Upvotes: 8