我有一個輸入欄位,我希望它隱藏,只有在下拉選單中的選擇是“飛機型別”時才應該可見:這是 html 代碼:
<mat-form-field appearance="outline" class="width-1 col-4">
<mat-label>Type</mat-label>
<mat-select formControlName="typeId">
<mat-option *ngFor="let type of typeList" [value]="type.id">
{{ type.name }}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" class="width-1 col-4">
<mat-label>Type of Motor</mat-label>
<input
matInput
placeholder="Type of Motor"
formControlName="typeMotor"
name="typeMotor"
id="typeMotor"
/>
</mat-form-field>
第一個 mat-form-field 是下拉選單,第二個 mat-form-field 是我想在某些條件下隱藏或可見的欄位。

uj5u.com熱心網友回復:
在 TS 檔案中創建一個變數,typeId并[(ngModel)]="typeId"像這樣傳入 mat-select 。然后像這樣在輸入上添加 ngIF 條件*ngIf="typeId == 4"
uj5u.com熱心網友回復:
我會采用可觀察的方法并將可觀察的附加到[hidden]. 您可以收聽valueChanges表單控制元件并采取相應措施。請記住,即使您隱藏了表單控制元件,它仍然存在于您的表單中,也許您還想禁用它,那么它甚至不會出現在表單值中,除非您呼叫getRawValue(). 所以我建議如下:
isHidden$: Observable<boolean>;
// build your form, then call
this.isHidden$ = this.myForm.get('typeId').valueChanges.pipe(
map((value: number) => {
return this.typeList.find((x) => x.id === value)?.name !==
'Type of Aircraft';
})
);
然后將此附加到您的輸入:
<input
matInput
[hidden]="isHidden$ | async"
placeholder="Type of Motor"
formControlName="typeMotor"
name="typeMotor"
id="typeMotor"
/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/371070.html
