I have custom Angular Component modal-component
that serves as a proxy for MatModalDialog
with ngTemplateOutlet
as body for mat-dialog-content
.
<mat-dialog-content class="modal-dialog-medium">
<ng-container *ngIf="dialogData.ngTemplateOutlet" [ngTemplateOutlet]="dialogData.ngTemplateOutlet"></ng-container>
</mat-dialog-content>
I also have custom Angular Component form-component
for forms – input some config of the form and controls.
This form-component
has getter method valid
that returns boolean
that states whether the formGroup
is valid or not.
The submit button is outside of form-component
– inside mat-dialog-actions
and this button needs to be disabled based on whether the form is valid or not. This is ensured by callback in injected MAT_DIALOG_DATA
//this.matDialog.open(ModalComponent, {data: ....
ngTemplateOutlet: this.formTemplate,
okButtonDisabled: () => !this.formComponent?.valid
<!-- modal-component -->
<button-component (click)="dialogData.okButtonAction && dialogData.okButtonAction()"
[disabled]="dialogData.okButtonDisabled && dialogData.okButtonDisabled()"
[text]="dialogData.okButtonText || 'OK'"></button-component>
As i said, the body of modal-component
is ngTemplateOutlet
, so my template looks something like this:
<ng-template #formTemplate>
<form-component *ngIf="formFields" [config]="formConfig"
[fields]="formFields" #formComponent (onSubmit)="submit()"></form-component>
</ng-template>
References to the elements:
@ViewChild('formTemplate') formTemplate: TemplateRef<any>;
@ViewChild('formComponent') formComponent: FormComponent;
When i call this.matDialog.open(...)
, the ngTemplateOutlet
renders into the view and FormComponent.valid
returns false. Right after the view is rendered, FormComponent.formGroup
is initialized and FormComponent.valid
becomes true. This triggers Expression has changed after it was checked
on [disabled]
.
I’ve encountered this error a few times past these days and I studied change detection and this error countless times trying to figure out how can i implement a clean solution that does not trigger this error, but i haven’t been able to (I’ve fixed 2 similar errors by calling change detection in ngAfterContentChecked
, but I can’t fix it here and i frankly don’t like it).
Am I missing something? Or am I just doing this wrong?