Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Tags Component
<ul>
<ng-template ngFor [ngForOf]="tags" let-tag let-index="index">
<li>
{{tag}}
<button type="button" (click)="remove(index)">x</button>
</li>
</ng-template>
</ul>
<input type="text"
[(ngModel)]="newTag"
(keydown)="onInputKeyDown($event)"
placeholder="type some text and press Enter" />
export class TagsComponent implements OnChanges {
@Input() tags: string[];
@Output() tagsChange = new EventEmitter<string[]>();
newTag = '';
constructor() { }
ngOnChanges() {
this.tags = this.tags || [];
}
remove(index: number) {
this.tags.splice(index, 1);
this.copyAndEmit();
}
onInputKeyDown($event: KeyboardEvent) {
if ($event.key === 'Enter') {
this.tags.push(this.newTag);
this.copyAndEmit();
this.newTag = '';
} else if ($event.key === 'Backspace' && this.newTag === '') {
this.tags.pop();
this.copyAndEmit();
}
}
private copyAndEmit() {
this.tags = this.tags.slice(0);
this.tagsChange.emit(this.tags);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment