[英]ng-select not updating in Angular 2
你好,我是 angular 2 的新手
我可以在 ng-select 控件中添加 formGroup 並預定義添加值。
那是完美的。 但是當按鈕單擊然后新值推送 ng-select 但 ng-select not updates 。
這是我的笨蛋
https://plnkr.co/edit/Hwfk1T2stkiRcLTxuFmz
//our root app component
import {Component, OnInit, NgModule, ViewChild} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {FormControl, FormGroup, ReactiveFormsModule} from '@angular/forms';
import {SelectModule} from 'ng-select';
@Component({
selector: 'my-app',
template: `
<h1>ng-select demo app</h1>
<form style="padding:18px;max-width:800px;"
[formGroup]="form">
<div style="margin:5px 0;font-weight:600;">Single select example</div>
<ng-select
[options]="options0"
[multiple]="false"
placeholder="Select one"
formControlName="selectSingle"
>
</ng-select>
<button (click)="pushValue()">Click</button>
<div>Events:</div>
<pre #preSingle>{{logSingleString}}</pre>
</form>`
})
export class App implements OnInit {
form: FormGroup;
multiple0: boolean = false;
options0: any[] = [];
selection: Array<string>;
@ViewChild('preSingle') preSingle;
logSingleString: string = '';
constructor() {
this.options0.push({"label":'test',"value":'Test'});
console.log("Object:::"+JSON.stringify(this.options0));
}
ngOnInit() {
this.form = new FormGroup({});
this.form.addControl('selectSingle', new FormControl(''));
console.log("Object:::"+JSON.stringify(this.options0));
}
pushValue()
{
console.log("pushValue call.");
this.options0.push({"label":"test","value":"Test"});
console.log("Object:::"+JSON.stringify(this.options0));
}
}
@NgModule({
imports: [
BrowserModule,
ReactiveFormsModule,
SelectModule
],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
哪里錯了???
您可以使用Array.slice()
更新到數組實例,以便讓 angular 檢測到數組的變化。
this.options0 = this.options0.slice();
查看ng-select
源代碼,我注意到
ngOnChanges(changes: any) {
if (changes.hasOwnProperty('options')) {
this.updateOptionsList(changes['options'].isFirstChange());
}
所以為了更新選項列表,你應該觸發ngOnChanges
。 可以通過創建對options0
新引用來options0
this.options0 = this.options0.concat({"label":"test","value":"Test"});
或
this.options0 = [...this.options0, {"label":"test","value":"Test"}];
變化檢測
Ng-select 組件實現OnPush
更改檢測,這意味着臟檢查檢查不可變數據類型。 這意味着如果您進行對象突變,例如:
this.items.push({id: 1, name: 'New item'})
組件不會檢測到更改。 相反,您需要執行以下操作:
this.items = [...this.items, {id: 1, name: 'New item'}];
這將導致組件檢測更改和更新。 有些人可能會擔心這是一個ngDoCheck
操作,但是,它比運行ngDoCheck
並不斷地比較數組的性能要高得多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.