I have a form in which I dynamically add some FormControl as the user adds elements. There's only one problem. Adding a FormControl will trigger the ngSubmit event, even though it should not be the behaviour I'm looking for.
Here's the relevant code :
public entityTypeForm: FormGroup;
constructor(private fb: FormBuilder) {
}
ngOnInit(): void {
this.fcName = new FormControl('', [Validators.required, Validators.maxLength(50)]);
this.entityTypeForm = this.fb.group({
name: this.fcName
});
}
addProp() {
let key = uuid.v4();
let prop: EntityTypeProperty = {
key: key,
name: "Some prop name"
};
let fc = new FormControl(prop.name, [Validators.required, Validators.maxLength(50)]);
this.entityTypeForm.addControl(prop.key, fc);
}
controlNames(): string[] {
return Object.keys(this.form.controls);
}
submit() {
this.entityTypeForm.markAsPristine();
this.entityTypeForm.markAsUntouched();
}
And HTML :
<form [formGroup]="entityTypeForm" (ngSubmit)="submit()">
<input
*ngFor="let name of controlNames()"
type="text"
[formControlName]="name">
<button (click)="addProp()"></button>
<button type="submit"></button>
</form>
Is there anything wrong with the way I add the FormControls that would create this weird behaviour?