2

你好,我是 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 {}

哪里错了???

4

3 回答 3

7

您可以使用Array.slice()更新到数组实例以让角度检测数组的变化。

this.options0 = this.options0.slice();
于 2017-06-30T05:11:20.573 回答
5

查看ng-select我注意到的源代码

ngOnChanges(changes: any) {
  if (changes.hasOwnProperty('options')) {
     this.updateOptionsList(changes['options'].isFirstChange());
  }

所以为了更新选项列表,你应该开火ngOnChanges。可以通过创建新的引用来完成options0

this.options0 = this.options0.concat({"label":"test","value":"Test"});

或者

this.options0 = [...this.options0, {"label":"test","value":"Test"}];

修改后的 Plunker

于 2017-06-30T05:09:42.687 回答
1

变化检测

ng-select 组件实现OnPush了变化检测,这意味着脏检查检查不可变的数据类型。这意味着如果您进行对象突变,例如:

this.items.push({id: 1, name: 'New item'})

组件不会检测到更改。相反,您需要这样做:

this.items = [...this.items, {id: 1, name: 'New item'}];

这将导致组件检测到更改和更新。有些人可能会担心这是一项昂贵的操作,但是,它比运行ngDoCheck和不断地对数组进行差异化要高效得多。

于 2021-01-28T09:17:39.990 回答