[英]Angular2 Update View from Array in Backend Service
我有一個ListComponent和EntryComponent用於將一個項目追加到列表中。 通過DataService將項目推入列表時,該列表不會在ListComponent中更新。 關於angular2的解決方法有什么想法嗎?
清單服務:
import {Injectable} from "angular2/core";
@Injectable()
export class DataService{
public items:Array<any> = [];
addItem(item:string):void{
this.items.push(item);
console.log(this.items);
}
}
簡單列表組件:
import { Component, Input, Output } from 'angular2/core';
import {ChangeDetectionStrategy} from "angular2/core";
@Component({
selector: "list",
template: "<div><ul><li *ngFor='#item of items'>{{item}}</li></ul>",
changeDetection:ChangeDetectionStrategy.OnPush
})
export class ListComponent{
@Input() items:Array<any>;
}
條目組件:
import {Component,EventEmitter, Output} from "angular2/core";
@Component({
selector:'entry-form',
template:'<div><input type="text" #myinput (keyup.enter)="emitEntry(myinput)"/></div>'
})
export class EntryComponent{
@Output() newEntry = new EventEmitter();
emitEntry(input):void{
this.newEntry.emit(input.value);
input.value="";
}
}
應用程序組件(根組件):
import { Component } from 'angular2/core';
import { ListComponent } from './list.component';
import {DataService} from './list-service';
import {EntryComponent} from './entry-form';
@Component({
selector:'my-app',
directives:[ListComponent,EntryComponent],
providers:[DataService],
template:
"<list [items]='listService.items' ></list> " +
"<entry-form (newEntry)='listService.addItem($event)'></entry-form> "
})
export class AppComponent{
constructor(public listService: DataService){
}
}
編輯通過將以下行添加到DataService中的addItem()方法中,我能夠產生正確的結果:
this.items = this.items.splice(0,this.items.length-1);
但是,這似乎不是angular2方式。
提前致謝!
編輯這是代碼的一大堆
刪除“ changeDetection:ChangeDetectionStrategy.OnPush”
只需將組件放在:
@Component({
selector: "list",
template: "<div><ul><li *ngFor='#item of items'>{{item}}</li></ul>"
})
你可以在這里看到
使用ChangeDetectionStrategy.OnPush
,Angular將僅在組件的輸入屬性中的至少一個發生更改的情況下檢查組件的數據綁定(例如模板中的{{item}}
)。 另一個重要的信息是,對於作為數組的輸入屬性,Angular更改檢測僅檢查數組以進行引用更改–即,它僅檢查數組引用是否已更改,而不查看數組的內容。
由於當您從服務器Listcomponent
新項push()
新數組時,數組輸入屬性items
繼續指向(引用)同一數組,因此角度更改檢測不會認為該數組已更改,因此未檢測到Listcomponent
輸入屬性更改,因此它不會檢查組件的數據綁定。
刪除ChangeDetectionStrategy.OnPush
之所以起作用,是因為默認情況下,即使輸入屬性未更改,Angular更改檢測也會檢查所有數據綁定。 由於您對數組的每個元素都有綁定,因此更改檢測將注意到在重新評估ngFor
時,存在一個新的綁定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.