這是一個關于基于formControl應用程式中的格式化文本的問題,其中使用 formControlFormBuilder和 formControl 陣列構建了 formControl。
它需要訪問 formControl 的當前值并根據該 formControl 值更改另一個元素的格式。
我在應用程式中有一個頁面,它是一個內置于 Ionic/Angular/Reactive 的庫存跟蹤表單。

內容來自資料庫訂閱。
您可以在表單中看到,當“應有”小于“實際有”時,專案的格式從紅色變為綠色。
此格式在模板檔案中使用 *ngIf 設定(參見箭頭 <------):
<form [formGroup]="inventoryForm" (ngSubmit)="onSubmit()">
<div formArrayName="ident">
<ion-item *ngFor="let item of inventoryElements; let i = index;">
<ion-grid>
<ion-row>
<ion-col *ngIf="item.current < item.par" style="color: red">
<strong>{{item.name}}</strong></ion-col <----------
>
<ion-col *ngIf="item.current >= item.par" style="color: green"
><strong>{{item.name}}</strong></ion-col <----------
>
<ion-col>{{item.par}} {{item.units}}</ion-col>
<ion-col>
<input size="1"
style="text-align: right;"
id="ident-{{ i }}"
type="text"
[formControlName]="i" />
{{item.units}}
</ion-col>
</ion-row>
</ion-grid>
</ion-item>
</div>
</form>
(注意:我可能應該將兩個 *ngIfs 更新為 *ngIf-else-template,但這不是這里的問題。)
當然,顏色是在加載表單時設定的。如果用戶更新實際擁有顏色不會改變。 隨著formControl值的變化而改變顏色是這里的問題。
表單控制元件陣列內置于ngOnInit():
ngOnInit() {
this.inventoryCollection = this.afs.collection('inventory', (ref) => {
this.query = ref;
this.query = this.query.orderBy('category');
return this.query;
});
this.inventoryInfo = this.inventoryCollection.snapshotChanges();
this.inventoryInfo.subscribe((actionArray) => {
// this map takes the firestore document name and makes it the ID
this.inventoryElements = actionArray.map((item) => ({
id: item.payload.doc.id,
...item.payload.doc.data(),
expanded: false,
}));
//======================= Here is where the control array is built ==================
this.ident.clear();
actionArray.forEach(item => {
this.ident.push(this.fb.control(item.payload.doc.data().current));
});
//==========================================================
});
}
(注意:我確定我清除陣列并在訂閱發出新值時重建它效率不高。很高興在那里有建議,但這不是核心問題。)
我試圖做但沒有成功的是*ngIf()使用 formControl.get() 函式更改專案顏色。但我無法獲得正確的語法。這是我嘗試過的:
<ion-col *ngIf="inventoryForm.get('0').value < item.par" style="color: red">
在我進行故障排除時,'0' 只是為了獲取一個值。顯然,當我們迭代inventoryElements.
** 問題:formArray為了在 *ngIf() 中進行比較,訪問 中控制元件值的正確方法是什么?**
uj5u.com熱心網友回復:
@Eliseo 有正確的答案。這個概念是將文本的 [style.color] 系結到一個比較。特別注意 引數的前面,使字串成為可以比較的數字。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/361689.html
上一篇:如何在GoogleAppEngine上請求我的服務?
下一篇:將HTML傳遞給自定義組件
