我有一个组件,里面有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-general
,data-additional
,test-component
和data-test2
是子组件。
答案 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
。