Skip to content

Instantly share code, notes, and snippets.

@kevinmerckx
Created November 6, 2018 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinmerckx/e602e89f67dc9851ce24051754557a96 to your computer and use it in GitHub Desktop.
Save kevinmerckx/e602e89f67dc9851ce24051754557a96 to your computer and use it in GitHub Desktop.
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