Angular反应形式验证

时间:2018-07-04 07:06:54

标签: angular-material angular5 angular-reactive-forms angular-formbuilder

我有一个包含3个输入的表单,其中2个是必需的,而第三个则不是。

我的问题是,当我进入表单页面时,看到不需要的字段处于有效状态,并且已经用绿色着色,即使该字段没有脏污也不被触摸。

>

在验证字段/表单之前还是可以做些什么使输入显示为灰色?

这是我在组件中使用的代码:

export class SystemSettingsComponent implements OnInit {
form: FormGroup;

constructor(private formBuilder: FormBuilder) {
    this.form = new FormGroup({});
}

ngOnInit() {
    this.form = this.formBuilder.group({
        serviceName: ['', Validators.required],
        serviceDesc: [''],
        serviceId: [{value: SystemSettingsComponent.generateId(), disabled: true}, Validators.required]
    });
}

static generateId() {
    return Math.random().toString(36).substr(2, 9);
}}

还有模板:

<form [formGroup]="form" novalidate>
<div class="row">
    <div class="col-lg-4">
        <mat-form-field>
            <input matInput placeholder="שם השירות" formControlName="serviceName"/>
        </mat-form-field>
        <mat-form-field>
            <textarea matInput placeholder="תיאור השירות" formControlName="serviceDesc"></textarea>
        </mat-form-field>
        <mat-form-field>
            <input matInput class="ltr text-align-left" placeholder="מזהה שירות" formControlName="serviceId"/>
        </mat-form-field>
    </div>
</div>
<div>
    <button mat-raised-button class="mat-raised-button mat-primary" matStepperNext>הבא</button>
</div>

1 个答案:

答案 0 :(得分:0)

您可以侦听表单的状态更改,并相应地设置可选表单控件的禁用状态。像这样:

ngOnInit() {
    this.form = this.formBuilder.group({
        serviceName: ['', Validators.required],
        serviceDesc: [{value: '', disabled: true}],
        serviceId: [{value: SystemSettingsComponent.generateId(), disabled: true}, Validators.required]
    });

    this.form.statusChanges.subscribe(status => {
        if (status === 'VALID' && this.form.controls.serviceDesc.disabled) {
            this.form.controls.serviceDesc.enable();
        } else if (status !== 'VALID' && this.form.controls.serviceDesc.enabled) {
            this.form.controls.serviceDesc.disable();
        }
    });
}