Search code examples
angulartypescriptformsangular-template

Angular ngForm inside ng-template


I have a form inside ng-template which is shown in a modal,

.ts
  @ViewChild('newControlForm', {static: false}) public newControlForm: NgForm;
.html
<ng-template>
    <form role="form" #newControlForm="ngForm">
</form>
</ng-template>

but since the form is inside ng-template its not able to get rendered that makes this.newControlForm to be undefined.

How can i solve this issue?


Solution

  • Use ng-template when you want to show something depending on some condition. See example

    Instead of:

    <div *ngIf="isDisplayed">Item 1</div>
    <div *ngIf="!isDisplayed">Item 2</div>
    

    You can do this:

    <div *ngIf="isDisplayed; else showItem2">Item 1</div>
    
    <ng-template #showItem2>
    Item 2
    </ng-template>
    

    But in your case, you permanently want to show ngForm than why using ng-template, just use div