首页 文章

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

提问于
浏览
1

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

我也关注了这个链接:Check if a form is valid from a parent component using Angular 4

每次我得到未定义的子组件形式的参考 .

我的代码是这样的 .

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转载......

1 回答

  • 1

    所以你想要的是将 parentForm.form.status 传递给带有 @Input() 的孩子 .

    在父html中:

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

    然后在你的孩子:

    @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中 .

    EDIT

    要发回验证:

    在子组件中,您必须触发@Output(),因此在html上使用change事件:

    @Output valid: EventEmitter<any> = new EventEmitter<any>();
    
    private checkValid(_childForm: string){
      if(_childForm === 'VALID'){
        this.valid.emit(true);
      }
      else { this.valid.emit(false);
    

    在html中你所有的孩子表格:

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

    在你的父html中:

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

    在父组件中:

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

相关问题