角度-与子组件的反应形式交互

时间:2019-09-19 09:34:22

标签: angular typescript

我有一个注册组件,该组件具有ng-switch组件

<ion-component>
  <ng-container [ngSwitch]="registrationStage">
    <step1 *ngSwitchCase="1"></step1>
    <step2 *ngSwitchCase="2"></step2>
    <step3 *ngSwitchCase="3"></step3>
  <ng-container>
</ion-component>

<ion-footer>
  <button (click)="goForward()">
  </button>
</ion-footer>

注册组件

  private goForward(): void {
    if (this.section !== 5) {
      switch (this.section) {
        case 1:
          this.step1.nextStep(); // <---cannot read property invalid of undefined
          this.regService.goForward();
          break;

        default:
          break;
      }
    } else {
      return;
    }
  }

step1组件

export class Step1 {
  private regForm: FormGroup;
  private formBuilder: FormBuilder;
  private stepTwo = false;

  public constructor(formBuilder: FormBuilder) {
    this.formBuilder = formBuilder;
  }
  public ngOnInit(): void {
    console.log('loaded'); //<-- I see this in the console

    this.regForm = this.formBuilder.group(
      {
        email: ['', [Validators.required, Validators.email]],
        password: ['', [Validators.required, Validators.minLength(6)]],
        confirmPassword: ['', Validators.required],
      },
      {
        validator: MustMatch('password', 'confirmPassword'),
      },
    );
  }
  public verifyAndNextStep(): void {
    this.stepTwo = true;

    if (this.regForm.invalid) {
      return;
    }
    const emailPassword: EmailPassword = {
      email: this.regForm.value.email,
      password: this.regForm.value.password,
    };
    this.regService.setEmailAndPassword(emailPassword);
    this.regService.goForward();
  }

问题是我收到一条错误消息:ERROR TypeError: Cannot read property 'invalid' of undefined指向上面的函数调用。此外,似乎FormGroup尚未初始化?

我不确定到底是什么问题,我看过其他有关此问题的帖子:

one

two

STACK BLITZ

2 个答案:

答案 0 :(得分:1)

您正在直接注入组件,而不是像这样从视图中获取它

  public constructor(navCtrl: NavController, step1: StepOne) {
}

这样的组件将是一个“纯对象”,而不会涉及angular的组件生命周期。因此,ngOnInit中没有调用Step1,因此没有创建任何形式,因此form是未定义的

应该做什么,而不是使用构造函数注入,而是使用@ViewChild从页面获取实际组件。

这可以解决您的问题(至少在第1步中,没有检查其他任何内容)

 @ViewChild(StepOne)
  private step1: StepOne;
  private navCtrl: NavController;
  public constructor(navCtrl: NavController) {
      this.navCtrl = navCtrl;
  }

https://stackblitz.com/edit/ionic-quz7y3?file=pages/home/home.ts

答案 1 :(得分:-1)

用(this.regForm.status ==='INVALID')替换(this.regForm.invalid)。

formbuilder没有无效/有效属性enter image description here