I have a "tags" component variable that generates a whitelist and a blacklist. Currently, I have a updateTagLists() function which will update the respective whitelist and blacklist but I have to make sure this function is called when necessary in order for the whitelist/blacklist to properly update. This seems counter-intuitive and feels incorrect. What's the correct way of having this.whitelist and this.blacklist automatically update when this.tags changes? Posted below is my component.
import { Component, OnInit } from '@angular/core';
import { Tag } from '../../models/tag';
import { TagService } from '../../services/tag.service';
@Component({
selector: 'app-admin',
templateUrl: './admin.component.html',
styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {
tags: any;
whitelist: Tag[];
blacklist: Tag[];
constructor(
private tagService: TagService
) {}
ngOnInit() {
this.tagService.getTags(1).then((tags) => {
this.tags = tags;
this.updateTagLists
});
}
updateTagLists() {
this.whitelist = this.tags.filter((tag: Tag) => tag.isWhitelisted );
this.blacklist = this.tags.filter((tag: Tag) => !tag.isWhitelisted );
}
whitelistAll() {
// Todo: Is there a better way of doing this where we aren't specifying the exact keys needed?
let updatedTags = this.tags.filter((tag) => !tag.isWhitelisted)
updatedTags = updatedTags.map((tag) => {
return { id: tag.id, name: tag.name, isWhitelisted: true, updated: true }
});
this.tags = updatedTags.concat(this.tags.filter((tag) => tag.isWhitelisted));
this.updateTagLists();
}
blacklistAll() {
// Todo: Is there a better way of doing this where we aren't specifying the exact keys needed?
let updatedTags = this.tags.filter((tag) => tag.isWhitelisted);
updatedTags = updatedTags.map((tag) => {
return { id: tag.id, name: tag.name, isWhitelisted: false, updated: true }
});
this.tags = updatedTags.concat(this.tags.filter((tag) => !tag.isWhitelisted));
this.updateTagLists();
}
handleToggle(event) {
if (!event) return;
let foundTag = this.tags.find( (tag) => event.id === tag.id );
foundTag.isWhitelisted = !event.isWhitelisted;
foundTag.updated = true;
this.updateTagLists();
}
}
isWhitelistedboolean on eachTag. I think that should just be sufficient and you should toggle it based on which one of the tags was clicked.