The use of the 'as' keyword in the code snippet above has caused some confusion for me. I am wondering why, if this.form.get('topics')
is already a formArray object, it needs to be returned as a FormArray again. This seems redundant to me, but upon further investigation, I discovered that returning this.form.get('topics')
directly would limit certain functions such as push, controls and removeAt. However, when I compared both
return this.form.get('topics') as FormArray;
and return this.form.get('topics')
by logging them into the console, they appeared to be exactly the same formArray object. This raises the question - why do I need to explicitly return it as a FormArray if it is already one? How does the 'as' keyword impact this situation?
@Component({
selector: 'ontime-course-form',
templateUrl: './ontime-course-form.component.html',
styleUrls: ['./ontime-course-form.component.scss']
})
export class OntimeCourseFormComponent {
form = new FormGroup({
topics: new FormArray([])
})
addTopic(topic: HTMLInputElement){
this.topics.push(new FormControl(topic.value))
}
removeTopic(topic: FormControl){
let index = this.topics.controls.indexOf(topic);
this.topics.removeAt(index);
}
get topics(){
return this.form.get('topics') as FormArray;
}
}