2016-05-12 26 views
0

我有評分,從一個postgres數據庫獲取並顯示在表中。 當我編輯評分時,我只能通過來自我的「TagInputComponent」的輸入元素添加或移除標籤。如何創建數組初始狀態的副本?

的TagInputComponent看起來是這樣的:

<taginput [tags]="datapoint.tags"></taginput> 

如何創建的tags副本oldTags一旦填滿數據:

import { Component, DoCheck, IterableDiffers, OnInit, Input, Output } from 'angular2/core'; 
import * as _ from 'underscore'; 

@Component({ 
    selector: 'taginput', 
    templateUrl: 'app/shared/taginput.component.html', 
    styleUrls: ['assets/stylesheets/taginput.css'] 
}) 
export class TagInputComponent implements OnInit, DoCheck { 
@Input() tags: string[]; 
newTag = ''; 
oldTags: string[]; 
differ: any; 

constructor(differs: IterableDiffers) { 
    this.differ = differs.find([]).create(null); 
} 

ngOnInit() { } 

ngDoCheck() { 
    var changes = this.differ.diff(this.tags); 

    if (changes) { 
     changes.forEachAddedItem(r => console.log('added ' + r.item)); 
     changes.forEachRemovedItem(r => console.log('removed ' + r.item)); 
    } 
} 

它得到的DataFormComponenet這樣用嗎?

它注意到ngOnInit()爲時尚早,因爲數據還沒有來自服務。隨着ngDoCheck()它總是更新到當前狀態。

這似乎是一個簡單的任務,但我不知道如何去做。


igorzg答案爲我工作,雖然我改變了我的需要。這是我所做的:

ngDoCheck() { 
    var changes = this.differ.diff(this.tags); 

    if (changes) { 
     if (Array.isArray(changes.collection) && !this.oldTags) { 
      this.oldTags = changes.collection.slice(); 
     } 

     changes.forEachAddedItem(r => console.log('added ' + r.item)); 
     changes.forEachRemovedItem(r => console.log('removed ' + r.item)); 
    } 
} 

回答

3
ngOnChanges(changes) { 
    if (Array.isArray(changes.tags) && !this.oldTags) { 
    this.oldTags = changes.tags.slice(); 
    } 
} 
1

setter?

@Input() 
set tags(tags: string[]) { 
    this.oldTags = tags.slice(); 
    _tags = tags; 
}