如何在Angular中验证父组件?

时间:2017-09-22 07:35:53

标签: angular

我有一个组件,里面有4-5个组件。如果未选择或填写任何表单的必填字段,我想禁用“保存”按钮。

 
<p-tabView>
    <p-tabPanel header="General" [selected]="true">
        <data-general [data]="data" (modalSave)="childData($event)">
        </data-general>
    </p-tabPanel>
    <p-tabPanel header="Additional" *ngIf="this.isEditData">
        <data-additional [data]="data" (modalSave)="additionalValid($event)">
        </data-additional>
    </p-tabPanel>
    <p-tabPanel header="Test" *ngIf="this.isEditData">
        <test-component></test-component>
    </p-tabPanel>
    <p-tabPanel header="Test2" *ngIf="this.isEditData">
        <data-test2></data-test2>
    </p-tabPanel>
</p-tabView>

<button type="submit" class="btn btn-primary" 
     [disabled]="!isFormValid()" (click)="onSubmitBtnClick()">Save</button>

我尝试实现方法isFormValid,定义并检查属性以检查每个表单的有效性。但是我无法做到。

data-generaldata-additionaltest-componentdata-test2是子组件。

2 个答案:

答案 0 :(得分:3)

试试这样:

数据-general.component.html

<form name="dataGeneralForm" role="form" novalidate (ngSubmit)="onSubmit(dataGeneralForm)" #dataGeneralForm="ngForm">
    <input type="text" class="form-control" [(ngModel)]="data.name" name="name" id="name" required />
    <button type="submit">Children Button</button>
</form>

数据-general.component.ts

export class DataGeneralComponent {

    data: any = {};

    @Output() modalSave = new EventEmitter();

    onSubmit(dataGeneralForm: NgForm) {
        this.modalSave.next(dataGeneralForm);
    }

}

<强> parent.component.html:

<p-tabView>
    <p-tabPanel header="General" [selected]="true">
        <data-general (modalSave)="childData($event)"></data-general>
    </p-tabPanel>
</p-tabView>
<button type="submit" class="btn btn-primary" [disabled]="!parentForm?.valid">Save</button>

<强> parent.component.ts

import { NgForm } from '@angular/forms';

export class ParentComponent {
    parentForm: NgForm;

    childData(e) {
        this.parentForm = e;
    }
}

答案 1 :(得分:1)

我已经解决了这个问题,发布了我的解决方案,以便它可以帮助其他人。

指令:

import { Directive } from "@angular/core";
import { NgForm, ControlContainer } from '@angular/forms';

@Directive({
    selector: '[provide-parent-form]',
    providers: [
        {
            provide: ControlContainer,
            useFactory: function (form: NgForm) {
                return form;
            },
            deps: [NgForm]
        }
    ]
})
export class ProvideParentForm { }

父组件html:

<button type="submit" class="btn btn-primary" [disabled]="!formName.valid">Save</button>

子组件html: 在子组件中有div而不是form。