vig*_*age 4 typescript angular-material angular angular-material-stepper angular9
我有一个材料步进器,步进器的每个步骤都有表格。在那里,每个步骤都应该由与其关联的表单控制。
尽管这个问题已经在 SO 中提出,但这些问题的答案并不能解决我的问题。因此我才问。
父 HTML
<mat-horizontal-stepper linear #stepper>
<mat-step [stepControl]="frmStepOne">
<ng-template matStepLabel>Step One Details</ng-template>
<app-first-step #stepOne></app-first-step>
</mat-step>
<mat-step [stepControl]="frmStepTwo">
<ng-template matStepLabel>Step Two Details</ng-template>
<app-second-step #stepTwo></app-second-step>
</mat-step>
</mat-horizontal-stepper>
Run Code Online (Sandbox Code Playgroud)
在我的父组件中,我有以下内容。
@ViewChild('stepOne') stepOneComponent: FirstStepComponent;
@ViewChild('stepTwo') stepTwoComponent: SecondStepComponent;
get frmStepOne() {
return this.stepOneComponent ? this.stepOneComponent.frmStepOne : null;
}
get frmStepTwo() {
return this.stepTwoComponent ? this.stepTwoComponent.frmStepTwo : null;
}
Run Code Online (Sandbox Code Playgroud)
我的孩子类组件
frmStepOne: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.frmStepOne = this.formBuilder.group({
name: ['', Validators.required]
});
}
Run Code Online (Sandbox Code Playgroud)
子类 HTML
<mat-card>
<form [formGroup]="frmStepOne">
<mat-form-field>
<input matInput formControlName="name" matInput placeholder="Name" required>
</mat-form-field>
<mat-card-actions>
<button mat-raised-button matStepperNext class="nav-btn pull-right">Next</button>
</mat-card-actions>
</form>
</mat-card>
Run Code Online (Sandbox Code Playgroud)
现在,当我运行该应用程序时,在控制台中,我看到以下内容。
错误 错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。先前值:“stepControl:null”。当前值:'stepControl:[object Object]'。
正如我之前提到的,SO 中也有同样的讨论。例如,以下链接问题的答案和注释建议将表单初始化移至构造函数,而不是将其放在 onInit 中。我已经这样做了。
但是,我仍然收到错误。
这是我在 Stackblitz 上的项目 - https://stackblitz.com/github/vigamage/stepper-component-wise
有人可以建议如何解决这个问题吗?
谢谢..
基本上,角度在已经设置了两个值之后检测变化null。因此,您需要明确告诉 Angular 它应该运行更改检测。查看此演示代码
我删除了 using 的逻辑,get因为直接从 HTML 调用函数是一种不好的做法。它将被调用多次。尝试将控制台日志放入您的代码中并查看。
我已经使用ngAfterViewInitwithChangeDetectorRef来通知。
export class AppComponent implements AfterViewInit {
title = 'mat-stepper';
form1: FormGroup;
form2: FormGroup;
@ViewChild('stepOne') stepOneComponent: FirstStepComponent;
@ViewChild('stepTwo') stepTwoComponent: SecondStepComponent;
constructor(private cdr :ChangeDetectorRef){}
ngAfterViewInit(){
this.form1 = this.stepOneComponent.frmStepOne;
this.form2 = this.stepTwoComponent.frmStepTwo
this.cdr.detectChanges();
}
}
Run Code Online (Sandbox Code Playgroud)
这将解决该错误