I have ratings, that get fetched from a postgres database and displayed in a table. When I edit a rating, I can only add or remove tags to it through a input like element which comes from my "TagInputComponent".
The TagInputComponent looks like this:
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));
}
}
It gets used in the DataFormComponenet like this:
<taginput [tags]="datapoint.tags"></taginput>
How do I create a copy of tags to oldTags once it is filled with data?
It noticed that ngOnInit() is too early as the data is not yet there from the service. With ngDoCheck() it always updates to the currentState.
It seems like a simple task, but I just can't find out how to do it.
igorzg answer worked for me, although I changed it to my needs. This is what I did:
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));
}
}