First of all I just begin with Angular 2 and I\'m trying to build a nested form and validate it.
Here\'s part of my ts file:
ngOnInit() {
this.myFo
With nested Array. Here is a code sample wich I have tested and runs perfectly in angular6:
app.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormArray, FormBuilder, Validators, FormControl, NgControl } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
proxyMedia: FormArray;
formGroup: FormGroup;
constructor(
public formBuilder: FormBuilder
) {}
ngOnInit() {
this.formGroup = this.formBuilder.group({
test_name: ['', [Validators.required]],
tests: this.formBuilder.array([
this.initTestsForm()
])
});
}
initTestsForm(): any {
return this.formBuilder.group({
test_num: '',
categorie: '',
responses: this.formBuilder.array([
this.initElement('responses')
])
});
}
initElement(elementName: string): FormGroup {
if(elementName === 'proxy_media') {
return this.formBuilder.group(
{
prefixe: 'prefixe',
confid: 'confid'
}
);
} else if(elementName === 'tests') {
return this.formBuilder.group({
test_num: ['test_num', [Validators.required, Validators.minLength(2)]],
categorie: ['categorie', [Validators.required, Validators.minLength(2)]],
responses: this.formBuilder.array([
this.initElement('responses')
])
});
} else if(elementName === 'responses') {
return this.formBuilder.group({
code_response: ['code_response', Validators.required],
log_level: ['log_level', Validators.required]
});
}
}
addElement(formGroup: FormGroup, elementName: string): void {
const control = < FormArray > formGroup.controls[elementName];
control.push(this.initElement(elementName));
}
removeElement(formGroup: FormGroup, elementName: string, index: number): void {
const control = formGroup.controls[elementName];
control.removeAt(index);
}
onSubmit(o: any) {
console.log(o);
}
debug(data: any) {
console.warn('debug: data ');
console.warn(data);
console.warn('stop');
}
}
app.component.html:
Avaibility tests
Add this code at the bottom to debug:
form value:
{{formGroup.value | json}}