Search code examples
htmlangularangular-formsangular-formbuilder

Angular FormBuilder not applying element values when HTML added through javascript


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?


Solution

  • I have managed to overcome this problem by:

    1. Hard coding the form in html file.
    2. Creating the FormGroup with its FormControls in ngOnInit().
    3. Made a function to edit the values of the FormGroup using patchValue().