如何使 Angular Reactive Form 也需要禁用输入?

Mar*_*uol 2 angular angular-reactive-forms angular-forms angular-validator

我有一个输入,当用户单击对话框时将填充该输入。因此,为此我必须将其禁用,因为我不希望用户手动输入该值。唯一的问题是这个输入必须是必需的,而我到目前为止还做不到。

我尝试在输入中添加“required”指令,并尝试在创建表单时添加 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>
Run Code Online (Sandbox Code Playgroud)

即使输入中没有任何内容,unityForm 也是有效的

小智 6

尝试readonly代替disabled.