I used an input component that would take inputs and then add it to any array. Then I passed this array to chips component that would display chips.
Template that calls keyDown and blur to add chips on these two events. Called another component that displays chips passing the array of chips.
<form [formGroup]="form">
<mat-form-field appearance="outline">
<mat-label>Key Skills</mat-label>
<input matInput placeholder="Skills" (keydown)="onAddSkills($event)" (blur)="onBlurMethod()" formControlName="keySkills" name="keySkills">
</mat-form-field>
<div class="chip-list">
<chip-list [skills]="skills"></chip-list>
</div>
</form>
The component for this template
import {Component} from '@angular/core';
import { FormGroup, FormControl, FormBuilder } from '@angular/forms';
export interface Skills {
name: string;
}
@Component({
selector: 'key-skills',
templateUrl: 'key-skills.component.html',
styleUrls: ['key-skills.component.scss'],
})
export class KeySkillsComponent {
skills: Skills[] = [];
private form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
"keySkills": new FormControl()
});
}
onAddSkills(event) {
if (event.key === "Enter" || event.key===",") {
this.addSkillsToArray(this.form.value['keySkills']);
}
}
onBlurMethod() {
this.addSkillsToArray(this.form.value['keySkills'])
}
addSkillsToArray(skill) {
if ((skill || '').trim()) {
this.skills.push({name: skill.trim()});
}
this.form.reset();
event.preventDefault();
}
}
Chip List template
<mat-chip-list>
<mat-chip *ngFor="let skill of skills">
{{skill.name}}
<mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
</mat-chip>
</mat-chip-list>
and Component
import {Component, Input} from '@angular/core';
@Component({
selector: 'chip-list',
templateUrl: 'chip-list.component.html',
styleUrls: ['chip-list.component.scss'],
})
export class ChipListComponent {
@Input() skills;
}
Easy peasy. The results of all this is: 