目录
angular material步进器,每一步都有单独的组件 - 表达式更改后它已被检查错误
angulartypescriptangular-materialangular9angular-material-stepper
浏览量:81
编辑于:2023-01-13 22:10:55

我有一个material步进器,步进器的每一步都有表格。在那里,每个步骤都应由与其关联的表单控制。

尽管这个问题已经在SO中被问过,但这些问题的答案并不能解决我的问题。因此,我问。

父网页

<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> 

在我的父组件中,我有以下内容。

@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;
}

我的子类组件

frmStepOne: FormGroup;

constructor(private formBuilder: FormBuilder) {

    this.frmStepOne = this.formBuilder.group({
      name: ['', Validators.required]
    });
}

子类 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>

现在,当我运行应用程序时,在控制台中,我看到以下内容。

错误 错误: 表达式已更改之后已检查错误: 表达式 检查后已更改。以前的值:“步控制:空”。 当前值:“步控制:[对象对象]”。

正如我之前提到的,SO中也有关于同样的讨论。例如,以下链接问题的答案和注释建议将表单初始化移动到构造函数中,而不是将其放在 onInit 中。我已经这样做了。

每个步骤的Angularmaterial步进器组件

但是,我仍然收到错误。

这是我在Stackblitz上的项目-https://stackblitz.com/github/vigamage/stepper-component-wise

有人可以建议如何摆脱这个问题吗?

谢谢。。

解决方案:

基本上,Angular在已经将两个值的值设置为两个值后检测变化。因此,您需要明确告诉 angular 它应该运行更改检测。查看此演示代码null

我已经删除了使用的逻辑,因为直接从 HTML 调用函数是一种不好的做法。它将被多次调用。尝试将控制台日志放入代码中并查看。get

我已经用了一起通知。ngAfterViewInit``ChangeDetectorRef

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();
  }

}

这将解决错误