I am trying to semi-dynamically build a form on angular. I have this function which creates the form in component.ts and adds the form HTML. Now the problem is, when I use it, it does not apply the values to the form elements. It does work on the other hand if the HTML is hard coded and the FormGroup
is created at ngOnInit();
private createForm(): void {
this.displayForm2 = new FormGroup({
profileName: new FormControl('test')
});
document.getElementById('form-div').innerHTML =
`<form [formGroup]="displayForm2">
<label for="profileName">Name: </label>
<input type="text" formControlName="profileName"><br>
</form>`;
}
I think the problem is because the HTML is added through the function rather than hard coded but I am not 100% sure and don't know how to fix it, any ideas?
I have managed to overcome this problem by:
FormGroup
with its FormControls
in ngOnInit()
.FormGroup
using patchValue()
.