i am trying to create nested forms but i am stuck in the second level and not sure how the addAttribute and removeAttribute will look like ?
export class ExportFormComponent implements OnInit {
public exportForm: FormGroup;
constructor( private formBuilder: FormBuilder ) { }
ngOnInit() {
this.exportForm = this.formBuilder.group( {
dataType: [''],
items: this.formBuilder.array( [
this.initItem(),
] )
});
}
initItem() {
return this.formBuilder.group( {
exportExpression: [''],
description: [''],
updatable: [true],
attributes: this.formBuilder.array( [
this.initAttribute(),
] )
});
}
initAttribute() {
return this.formBuilder.group( {
exportExpression: [''],
localizedRawField: [''],
localizable: [true],
});
}
addItem() {
const control = <FormArray>this.exportForm.controls['items'];
control.push( this.initItem() );
}
removeItem( i: number ) {
const control = <FormArray>this.exportForm.controls['items'];
control.removeAt( i );
}
addAttribute() {
}
removeAttribute( ) {
}
save( exportConfiguration: ExportConfiguration ) {
console.log( exportConfiguration );
}
}
My interface tree
export interface ExportConfiguration {
dataType?: string,
items?: Item[],
}
export interface Item {
exportExpression?: string,
description?: string,
updatable?: boolean,
attributes?: Attribute[],
}
export interface Attribute {
exportExpression?: string,
localizable?: boolean,
localizedRawField?: string,
rules?: TransformationRule[]
}
export interface TransformationRule {
dataPathKey?: string,
expressionCheck?: boolean,
expression?: string,
}
EDIT
Okay so i used the demo posted as one of the answers but i get null in the following ( this.itemsCtrl.get( '${index}.attributes' ) as FormArray )
addAttribute( index: number ) {
( this.itemsCtrl.get( '${index}.attributes' ) as FormArray ).push( this.initAttribute() );
}