【发布时间】:2019-05-22 12:53:08
【问题描述】:
我有一个输入,当用户单击对话框时将填充该输入。所以为此我不得不禁用它,因为我不希望用户手动输入值。 唯一的问题是这个输入必须是必需的,而我目前无法做到。
我尝试在输入中添加“必需”指令,并尝试在创建表单时添加 Validator.required,但这些都没有使表单成为必需的字段。
createUnityForm(): FormGroup {
return this._formBuilder.group({
id : [this.unity.id],
description: [this.unity.description],
floor: [{value: this.unity.floor, disabled: true}, Validators.required]
});
}
<mat-form-field appearance="outline" floatLabel="always" class="mr-16" fxFlex>
<mat-label>{{'UNITY.FLOOR' | translate}}</mat-label>
<input matInput placeholder="{{'UNITY.SELECT-FLOOR' | translate}}"
name="floor"
formControlName="floor"
required>
</mat-form-field>
<button *ngIf="action === 'edit'"
mat-button
class="save-button"
(click)="matDialogRef.close(['save',unityForm])"
[disabled]="unityForm.invalid"
aria-label="save">
{{'GENERAL.SAVE' | translate}}
</button>
即使输入中没有任何内容,unityForm 也是有效的
【问题讨论】:
-
当我尝试在输入中添加 [disabled] = true 时,控制台中会显示角度:看起来您正在使用带有响应式表单指令的 disabled 属性。如果在组件类中设置此控件时将 disabled 设置为 true,则 disabled 属性实际上会在 DOM 中为您设置。我们建议使用这种方法来避免“检查后更改”错误。示例:form = new FormGroup({ first: new FormControl({value: 'Nancy', disabled: true}, Validators.required), });这正是我编码的。不工作
-
可能
this.unity.floor开头包含一个值。如果它有值,那么验证可能会通过 -
它没有.. 尝试使用 floor: [{value: null, disabled: true}, Validators.required] 以及问题仍然存在。
标签: angular angular-reactive-forms angular-forms angular-validator