- Use FormArray class to work with Array of objects in a form
form = new FormGroup({
topics: new FormArray([])
})
addTopic(topic: HtmlInputElement) {
this.topics.push(new FormControl(topic.value))
topic.value = "";
}
get topics() {
return this.form.get('topics') as FormArray;
}
removeTopic(topic: FormControl) {
let index = this.topics.controls.indexOf(topic);
this.topics.removeAt(index);
}
<form>
<input type="text" class="form-control" (keyup.enter)="addTopic(topic)" #topic>
</form>
<ul class="list-group">
<li *ngFor="let topic of topics.controls"
class="list-group-item"
(click)="removeTopic(topic)"
>
{{topic.value}}
</li>
</ul>