ng-select不在Angular 2中更新

时间:2017-06-30 04:58:28

标签: javascript angular angular-ngselect

你好,我是角色2的新人

我可以在ng-select controll和预定义的值中添加formGroup。

这是完美的。 但是当按钮点击时,新值按下ng-select但ng-选择不更新。

这里是我的plunker

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 {}

哪里错了???

3 个答案:

答案 0 :(得分:2)

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

this.options0 = this.options0.slice();

答案 1 :(得分:1)

查看我注意到的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"}];

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");

<强> Modified Plunker

答案 2 :(得分:1)

变化检测

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

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

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

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

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