gpt4 book ai didi

javascript - ng-select 没有在 Angular 2 中更新

转载 作者:行者123 更新时间:2023-11-30 11:35:00 24 4
gpt4 key购买 nike

你好,我是 Angular 2 的新手

我可以在 ng-select 控件中添加 formGroup 并预定义添加的值。

那是完美的。但是当单击按钮时,新值会推送到 ng-select 但 ng-select 不会更新。

这是我的傻瓜

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();

关于javascript - ng-select 没有在 Angular 2 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44838862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com