[英]Checkbox state not reflecting ngModel value in Angular 2
所以我的問題是我有一個復選框,其狀態未反映其ngModel值。 讓我解釋一下體系結構:我有一個管理產品列表的服務,以及一個應該顯示此列表並讓用戶選擇或取消選擇任何產品的組件。 如果用戶取消選擇一個產品並且沒有選定的產品了,我將嘗試全部重新選擇它們。 但是,當我這樣做時,觸發事件的復選框未更新(在圖形上,因為其ngModel已更新),而所有其他復選框均已正確更新。
這就是服務(我使用BehaviourSubject,以便我的組件可以偵聽其更改):
@Injectable()
export class ProductService {
private productsSubject: BehaviorSubject<Array<{name: string, selected: boolean}>>
public products = this.productsSubject.asObservable();
constructor() {
this.productsSubject.next([
{name: 'Product 1', selected: true},
{name: 'Product 2', selected: true},
{name: 'Product 3', selected: true}
]);
}
public select(name: string) {
// In this method I change "selected" for the corresponding product.
// if no product is selected, I select them all.
}
}
這是組件視圖:
<li *ngFor="let product of ProductService.products | async">
{{product.name}}{{product.selected}}
<input type="checkbox" [(ngModel)]="product.selected" (ngModelChange)="ProductService.select(product.name)">
</li>
對於組件本身,除了注入ProductService之外,它沒有其他任何特殊的事情。
最后,當我運行該應用程序時,一切正常,當我選中和取消選中復選框時,模型將更新,並且復選框狀態也將更新。 除了一種情況
開始:
Product 1 -> selected: true + checkbox ticked
Product 2 -> selected: false + checkbox not-ticked
Product 3 -> selected: false + checkbox not-ticked
我取消選中第一個產品,“選擇”方法完成了重新選擇所有產品的工作,而我有:
Product 1 -> selected: true + checkbox **NOT-TICKED**
Product 2 -> selected: true + checkbox ticked,
Product 3 -> selected: true + checkbox ticked
您知道為什么觸發事件的復選框沒有以圖形方式進行更新嗎?
預先感謝您的幫助。
當前,您正在使用單向數據綁定:
[ngModel]="product.selected"
使用雙向數據綁定:
[(ngModel)]="product.selected"
因此更改會反映在您的用戶界面中。
要使用ngModel,您需要具有名稱屬性,此外,如果您使用的是自舉樣式的復選框,它實際上會隱藏該復選框,在這種情況下,您需要在標簽上添加for="id"
。 通常,我設置<input type="checkbox" name="something" id="something" >
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.