如何验证与 Angular4 中的父组件具有 3 个不同 NgForm 的子组件 NgForms

How to validate the child component NgForms having 3 different NgForm from the parent component in Angular4

我有一个场景,我正在访问两个不同的 NgForms,一个在父表单 #parentform 中,另一个在子组件 #childForm & #childForm1 中,我想检查子表单控件的有效性是否有效不是父组件形式。如何在 angular4 中执行此操作。

我也关注了这个link:

每次我对子组件表单的引用都未定义。

我的代码是这样的。

parent.component.html

    <form class="form-wrapper" (ngSubmit)="parentForm.form.valid && save()" #parentForm="ngForm" novalidate>
        <input id="firstName" type="text" placeholder="" class="validate" name="firstName" [(ngModel)]="firstname_" #firstName="ngModel"                         required>
    </form>
    <child-component></child-component>

child.component.html

  <form class="form-wrapper" (ngSubmit)="childForm.form.valid && save()" #childForm="ngForm" novalidate>
            <input id="phoneNumber" type="text" placeholder="" class="validate" name="phoneNumber" [(ngModel)]="phone_" #phoneNumber="ngModel"                       required>
 </form>

 <form class="form-wrapper" (ngSubmit)="childForm1.form.valid && save()" #childForm1="ngForm" novalidate>
            <input id="mobileNumber" type="text" placeholder="" class="validate" name="mobileNumber" [(ngModel)]="mobile_" #mobileNumber="ngModel" required>
 </form>

现在我想验证父表单中的子组件表单 "childForm" & "childForm1" 是否有效。

相同内容转载于 https://stackblitz.com/edit/angular-cjorjz...

所以你想要的是通过 @Input().

parentForm.form.status 传递给 child

在parent html:

<child-component [parent]="parentForm.form.status"></child-component>

然后在你的 child:

@Input() parent: any;
private boolean: boolean = false;

ngOnChanges(changes: any) {
  if(changes.dataSet.currentValue === 'VALID'){
    this.boolean = true;
  }
  else { this.boolean = false; }
}

并检查它 console.log(this.boolean) 或将 {{boolean}} 放入 html。或者 childForm.form.valid && save() && boolean 在 html.

编辑

要发回验证:

在 child 组件中,您必须触发 @Output(),因此在 html:

上使用更改事件
@Output valid: EventEmitter<any> = new EventEmitter<any>();

private checkValid(_childForm: string){
  if(_childForm === 'VALID'){
    this.valid.emit(true);
  }
  else { this.valid.emit(false);
}

在 html 中到所有 child 表单域:

(ngModelChange)="checkValid(childForm.form.status)"

在你的 parent html:

<child-component [parent]="parentForm.form.status" (valid)="setValidChild($event)"></child-component>

在 parent 组件中:

private childBoolean: boolean= false;

private setValidChild(_boolean: boolean){
  this.childBoolean = _boolean;
}