在Angular中单击父组件按钮时,验证子组件表单

时间:2018-10-04 01:37:22

标签: angular

我在父模板中有两个按钮。一个按钮充当父/子窗体的“提交”。另一个应验证子组件形式。单击“提交”按钮将同时验证两者-确定。但是,我无法通过另一个按钮来验证我的子组件表格。本质上,仅当单击“检查电话”按钮时,才显示子窗体的必需错误。

父模板:

    <form id="sampleform" [formGroup]="sampleForm" (ngSubmit)="formsubmit()">
  <mat-form-field>
    <input matInput type="text" formControlName="name" [errorStateMatcher]="matcher">
    <mat-error *ngIf="sampleForm.controls.name.hasError('required') && isShowErrors">This field is invalid</mat-error>
  </mat-form-field>
  <br/>
  <br/>
  <child-component [isShowErrors]="isShowErrors"></child-component>
</form>

<button type="button">Check phone</button> <br/>
<button type="submit" form="sampleForm" (click)="formsubmit()">Submit</button>

父项TS:

export class AppComponent{
  isShowErrors: boolean = false;
  sampleForm: FormGroup;
  matcher = new MyErrorStateMatcher();
  constructor(private fb: FormBuilder){

  }
  ngOnInit(){
    console.log(">>>>")
    this.sampleForm = this.fb.group({
      name: ['', Validators.required]
    });
  }

  formsubmit(){
    this.isShowErrors = true;
    console.log(this.sampleForm);
    if(this.sampleForm.valid){
      //navigate
    }
  }
}

子组件模板:

<form [formGroup]="sampleChildForm">
  <mat-form-field>
    <input matInput type="text" formControlName="phone" [errorStateMatcher]="matcher">
    <mat-error *ngIf="sampleChildForm.controls.phone.hasError('required') && isShowErrors">Test Error</mat-error>
</mat-form-field>
</form>

Stackblitz https://stackblitz.com/edit/angular-gyzaag

1 个答案:

答案 0 :(得分:0)

这是一次完整的工作突击……https://stackblitz.com/edit/angular-7nbjnh ...实现了本文给出的解决方案。

在子组件控制器中添加以下方法:

formsubmit(){
  this.isShowErrors = true;
  console.log(this.sampleChildForm);
  if(this.sampleChildForm.valid){
    //navigate
  }
}

在父组件html中更改以下行:

<child-component #fred [isShowErrors]="isShowErrors"></child-component>

<button type="button" (click)="checkPhone()">Check phone</button>

在父控制器中执行以下操作:

@ViewChild('fred') fred;

checkPhone() {
  this.fred.formsubmit()
}

这基本上允许父级在子级中调用方法。这里的关键是#fred参考变量。当您在有角度的组件上放置参考变量时,它可以访问组件类及其方法,因此您可以轻松地从父级调用child.formsubmit() AKA fred.formsubmit()

与此处无关,但值得了解,当您将引用变量放在HTML元素上时,它使您可以访问HTML元素(与getElementById一样)。

如果有兴趣,此方法会有新的细微变化,该方法仍使用@ViewChild,但此处不需要引用变量:

https://angular.io/guide/component-interaction#parent-calls-an-viewchild

此替代方法基本上相同,因为父级仍在子级中调用方法。联播仅略有不同。

如果您想使用替代方法,只需删除#fred参考变量,并在父控制器中对@ViewChild进行此操作:

import { ChildComponent } from './child/child.component';
@ViewChild(ChildComponent) private fred: ChildComponent;

我个人更喜欢使用引用变量,因为它似乎绑定得不太紧密,但是我相信后一种方法被认为是最佳实践,因为它在Component Interaction下的Angular文档中。

相关问题