0

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));
    }
}
0

2 Answers 2

3
ngOnChanges(changes) {
   if (Array.isArray(changes.tags) && !this.oldTags) {
     this.oldTags = changes.tags.slice();
   }
}
Sign up to request clarification or add additional context in comments.

Comments

1

How about setter?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.