将ng-template插入子组件不会渲染传入的模板

时间:2019-03-01 12:42:03

标签: angular

我有一个称为auth的父组件。在此组件中,我有一个ng-template,它是一个表示登录/注册表单的表单,如下所示:

`<ng-template #authForm>
    <form [formGroup]="authForm" (ngSubmit)="onSubmit()">
      <mat-form-field>
        <input matInput placeholder="Username" formControlName="userName" >
        <mat-error *ngIf="postForm.get('userName').invalid">You must enter a value</mat-error>
      </mat-form-field>
      <mat-form-field>
        <input matInput placeholder="E-mail" formControlName="email" >
        <mat-error *ngIf="postForm.get('email').invalid">You must enter a value</mat-error>
      </mat-form-field>
      <mat-form-field>
        <input matInput placeholder="Password" formControlName="password" type="password">
        <mat-error *ngIf="postForm.get('password').invalid">You must enter a value</mat-error>
      </mat-form-field>
    </form>
  </ng-template>`

在同一父组件中,我正在使用角材料mat-tab-group组件来显示登录组件或注册组件:

`<mat-tab-group (selectedTabChange)="onSignup($event)">
    <mat-tab label="Login">
        <ng-container *ngIf="!isSignup">
            <app-login [loginForm]="authForm"></app-login>  
          </ng-container>
    </mat-tab>
    <mat-tab label="Sign Up"> 
        <ng-container *ngIf="isSignup">
            <app-signup></app-signup>
          </ng-container>
    </mat-tab>
</mat-tab-group>`

在子组件上,例如LoginComponent。我有一个@Input() loginForm: TemplateRef<any>。每当我尝试渲染传入的模板时,都不会显示任何内容,而且我也不知道为什么它不起作用:

`<ng-container 
  *ngTemplateOutlet="loginForm">
</ng-container>`

Inspecting the template element in the console produces these results

1 个答案:

答案 0 :(得分:1)

问题是您有两个authForm变量名。将ng-template名称更改为其他名称,如下所示。工作示例Stackblitz

<ng-template #authFormTemplate>
    <form [formGroup]="authForm" (ngSubmit)="onSubmit()">
      <mat-form-field>
        <input matInput placeholder="Username" formControlName="userName" >
        <mat-error *ngIf="postForm.get('userName').invalid">You must enter a value</mat-error>
      </mat-form-field>
      <mat-form-field>
        <input matInput placeholder="E-mail" formControlName="email" >
        <mat-error *ngIf="postForm.get('email').invalid">You must enter a value</mat-error>
      </mat-form-field>
      <mat-form-field>
        <input matInput placeholder="Password" formControlName="password" type="password">
        <mat-error *ngIf="postForm.get('password').invalid">You must enter a value</mat-error>
      </mat-form-field>
    </form>
  </ng-template>

<mat-tab-group (selectedTabChange)="onSignup($event)">
    <mat-tab label="Login">
        <ng-container *ngIf="!isSignup">
            <app-login [loginForm]="authFormTemplate"></app-login>  
          </ng-container>
    </mat-tab>
    <mat-tab label="Sign Up"> 
        <ng-container *ngIf="isSignup">

          </ng-container>
    </mat-tab>
</mat-tab-group>

enter image description here