如果子组件字段无效,如何禁用“父组件表单提交”按钮

时间:2018-07-26 07:58:49

标签: angular angular2-forms angular6 angular4-forms angular-validation

我正在使用模板驱动表单。

父组件HTML

<form #BasicForm="ngForm" (ngSubmit)="onBasicDetailsSubmit()" id="BasicForm">

  <app-input-text [(sharedVar)]="dashboardDetails.Text1" [isMandatory]="true" ></app-input-text>
  <app-input-text [(sharedVar)]="dashboardDetails.Text2" [isMandatory]="false"></app-input-text>

  <input type="submit" value="Save" [disabled]="!BasicForm.valid" class="btn btn-success">

</form>

子组件

TS

@Input() sharedVar: number;
@Input() isMandatory: boolean;

@Output() sharedVarChange = new EventEmitter();


change(newValue) {
  this.sharedVar = newValue;
  this.sharedVarChange.emit(newValue);
}

HTML

<input type="text" class="form-control" [(ngModel)]="sharedVar" (ngModelChange)="change($event)" [attr.required]="isMandatory">

“提交”按钮未被禁用。我尝试在子组件以及父组件选择器中编写required,但是它不起作用。请帮忙。

3 个答案:

答案 0 :(得分:1)

在使用Template-Driven-Form时,验证Child components的最佳方法是创建一个custom-Directive,您将始终将其添加到要验证的每个字段中。 -组件形式:

您可以使用这个:

import {Directive, OnInit} from '@angular/core';
import {NgControl, NgForm, NgModel} from "@angular/forms";

/**
 * This attribute directive must be used to each input-field of a childComponent.
 * That input-field must contain a NgModel attribute, else the application must throw an error
 * Usage: (<input class="form-control" type="text" registerChildComponentToForm
 *          [(ngModel)]="testname" name="testname" required />
 */

@Directive({
    selector: '[registerChildComponentToForm]',
    providers: [NgModel]
})
export class RegisterTemplateFormModelDirective implements OnInit {

    constructor(private form: NgForm, private eltControl: NgControl) {
    }

    ngOnInit() {
        if (this.form && this.eltControl) {
            this.form.form.addControl(this.eltControl.name, this.eltControl.control);
        }
    }

}

然后将其注册到declarations中的exportsApp-Module

declarations: [
        RegisterTemplateFormModelDirective,
        ...
],
exports: [
        RegisterTemplateFormModelDirective,
        ...
]

假设您的<app-input-text>是这段HTML代码,那么您应该像这样使用directiveregisterChildComponentToForm):

<input id="iban" name="iban" [(ngModel)]="bank.iban" #ibanRef="ngModel" 
  [required]="isMandatory" registerChildComponentToForm/>

答案 1 :(得分:0)

父组件HTML

<app-input-text [(sharedVar)]="dashboardDetails.Text1" (sharedVarChange)="sharedVarChangeHandle($event)" ...

父组件TS

sharedVarChangeHandle($event) {
    // by evaluating the value passed you can update a variable (ex: disableSubmit)
} 

父组件HTML

<input type="submit" value="Save" [disabled]="!disableSubmit" class="bt .....

答案 2 :(得分:0)

子组件ts

valid // this is a public variable

change(newValue) {
  this.sharedVar = newValue;
  this.sharedVarChange.emit(newValue);
  // here conditioanally update the **valid** variable (true or false)
}