Search code examples
htmlangularformsng-templateng-container

How to render ng-template dynamically with Template Reference in Angular


I tried the example in this question Dynamic ngTemplateOutlet value but still, no success.

I want to dynamically display an ng-template form based on the option selected by the user.

I have defined global variables and 3 forms with their Template References in my component.ts

@ViewChild('formA', {static: false}) formAref: TemplateRef<any>;
formA = new UserForm('formA', 'Mus Mauris Form', this.formAref);

@ViewChild('formB', {static: true}) formBref: TemplateRef<any>;
formB = new UserForm('formB', 'Vitae Purus Faucibus Form ', this.formBref);

@ViewChild('formC', {static: true}) formCref: TemplateRef<any>;
formC = new UserForm('formC', 'Aliquet Nec Form', this.formCref);


selectedForm: TemplateRef<any>;
totalForms: UserForm[] = [];

where UserForm is defined as

interface UserFormInterface {
  id: string;
  display: boolean;
  submitFunc: Function;
}

class UserForm implements UserFormInterface {
  id: string;
  form_name: string;
  display: boolean;
  submitFunc: Function;
  reference: TemplateRef<any>;

  constructor(id: string, form_name: string, reference: TemplateRef<any>) {
    this.id = id;
    this.form_name = form_name;
    this.reference = reference;
  }
}

In my HTML template I have the following

<div id="inner-form-dashboard" class="row">
      <div id="form-list" class="col-4">
          <div
               *ngFor="let form of totalForms" 
              class="form-item d-flex flex-column justify-content-around align-items-center">
              <div class="form-link" (click)="showForm(form)">{{form.form_name}}</div>
          </div>
      </div>
      <div id="form-container" class="col-8 d-flex flex-column justify-content-between">
          <div *ngFor="let form of totalForms">
              <ng-container *ngIf="form.display" style="display: block;">
                {{form.id}}
                  <div
                      *ngTemplateOutlet='selectedForm'>
                  </div>
              </ng-container>
          </div>  
      </div>
</div>

<ng-template #formA>
    <form>
        <div class="form-group">
            <label for="exampleFormControlInput1">Email address</label>
            <input type="email" class="form-control" id="exampleFormControlInput1" placeholder="[email protected]">
        </div>
        <div class="form-group">
            <label for="exampleFormControlSelect1">Example select</label>
            <select class="form-control" id="exampleFormControlSelect1">
            <option>1</option>
            <option>2</option>
            <option>3</option>
            <option>4</option>
            <option>5</option>
            </select>
        </div>
        <div class="form-group">
            <label for="exampleFormControlTextarea1">Example textarea</label>
            <textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
        </div>
    </form>
</ng-template>

The first column col-4 will determine which form to display on the second column col-8 based on which item is clicked on the left.

enter image description here

When I click on the left item, I can see that the form.id is displayed on the right side, meaning that the selection of the forms and the ngFor are working properly, however, the templates on line *ngTemplateOutlet='selectedForm'> are not displayed.

The functionality looks like this in my component

showForm(form: UserForm): void {
    this.totalForms.forEach(f => f.display = false);
    form.display = true;
    this.selectedForm = form.reference;
    console.log(form);
    console.log('selected', this.selectedForm);
  }

https://stackblitz.com/edit/angular-34r1gw

https://angular-34r1gw.stackblitz.io


Solution

  • The cause of your issue is that you are attempting to use the template references too early. The earliest that @ViewChild properties with { static: true } are available is in the ngOnInit lifecycle hook:

    ngOnInit() {
      this.formA = new UserForm('formA', 'Mus Mauris Form', this.formAref);
      this.formB = new UserForm('formB', 'Vitae Purus Faucibus Form ', this.formBref);
      this.formC = new UserForm('formC', 'Aliquet Nec Form', this.formCref);
      this.totalForms.push(this.formA, this.formB, this.formC);
    }
    

    When using { static: false }, then the earliest that the @ViewChild properties are available is in the ngAfterViewInit lifecycle hook.

    StackBlitz Example