Issue
How should I declare this type ?
Let say I've a FormGroup
- I instantize it in the constructor.
export interface MyType {
myValue: string
}
myForm: FormGroup
myArray: FormArray // <FormControl<MyType>>
constructor(private _formBuilder: FormBuilder) {
myForm = new FormGroup({
myArray: this._formBuilder.array([])
})
}
- Because I have somewhere a button that let me add a new element to the array, I do as follow
addElement() {
this.myArray = this.myForm.get('myArray') as unknown as FormArray
this.myArray.push(this.newElement())
}
private _newElement(): FormGroup { // What type to use ?
return this._formBuilder.group({
myValue: ''
})
}
But when I do use the
myArray: FormArray<FormControl<MyType>>
I get the following error
Argument of type 'FormGroup<any>' is not assignable to parameter of type 'FormControl<MyType>'.
Type 'FormGroup<any>' is missing the following properties from type 'FormControl<MyType>': defaultValue, registerOnChange, registerOnDisabledChange
Somebody knows
- which type I should here
private _newElement(): FormGroup { // What type to use ?
or - Is this correct
myArray: FormArray<FormControl<MyType>>
? ->FormGroup<FormControl<MyType>>
being incorrect
Solution
- Declare the interface/class for the Typed Form.
export class MyTypeForm {
myValue: FormControl<string>;
}
- Declare
myArray
type asFormArray<FormGroup<MyTypeForm>>
.
myArray: FormArray<FormGroup<MyTypeForm>>;
- The
_newElement
method to returnFormGroup<MyTypeForm>
type.
private _newElement(): FormGroup<MyTypeForm> {
return this._formBuilder.group<MyTypeForm>({
myValue: this._formBuilder.control(''),
});
}
Reference: Angular Strictly Typed Forms (Complete Guide)
Answered By - Yong Shun
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.