Hot*_*mit 2 javascript angular-ngselect angular
你好,我是 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 {}
Run Code Online (Sandbox Code Playgroud)
哪里错了???
您可以使用Array.slice()更新到数组实例,以便让角度检测数组的变化。
this.options0 = this.options0.slice();
Run Code Online (Sandbox Code Playgroud)
查看ng-select源代码我注意到
ngOnChanges(changes: any) {
if (changes.hasOwnProperty('options')) {
this.updateOptionsList(changes['options'].isFirstChange());
}
Run Code Online (Sandbox Code Playgroud)
所以为了更新选项列表,你应该火ngOnChanges。它可以通过创建新的引用来完成options0
this.options0 = this.options0.concat({"label":"test","value":"Test"});
Run Code Online (Sandbox Code Playgroud)
或者
this.options0 = [...this.options0, {"label":"test","value":"Test"}];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2514 次 |
| 最近记录: |