【问题标题】:How to change Angular components at runtime in root component如何在运行时在根组件中更改 Angular 组件
【发布时间】:2019-09-05 03:39:16
【问题描述】:

我想添加一个动态表单。当按下配置按钮时,表单应该从app-login-form变为login-config-form

app.component.html

<div class="container p-5">
  <app-login-header></app-login-header>
  <div class="load-form">
    <login-config-form></login-config-form> 
    <app-login-form></app-login-form>
  </div>
</div>

app.component.ts

import {
  Component,
} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {

}

【问题讨论】:

    标签: angular typescript angular-components


    【解决方案1】:

    类似

    <div class="container p-5">
      <app-login-header></app-login-header>
      <div class="load-form">
        <button (click)="displayConfig = !displayConfig">Toggle</button>
        <login-config-form *ngIf="displayConfig"></login-config-form> 
        <app-login-form> *ngIf="!displayConfig"</app-login-form>
      </div>
    </div>
    

    TS:

    //...
    export class AppComponent {
       public displayConfig: boolean;
    }
    

    【讨论】:

    • 没有更好的办法吗? &lt;template #form&gt;&lt;/template&gt; 之类的东西和我的 AppComponent 控制要加载的表单。
    【解决方案2】:

    你可以试试吗:

    <div class="container p-5">
      <app-login-header></app-login-header>
      <div class="load-form">
        <button (click)="displayConfig = !displayConfig">Toggle</button>
    
        <!-- If is displayConfig then show login-config -->
        <ng-container *ngIf="displayConfig; else isLoginForm;">
          <login-config-form></login-config-form>
        </ng-container>
    
        <!-- else show isLoginForm -->
        <ng-template #isLoginForm>
          <app-login-form></app-login-form>
        </ng-template>
    
    
      </div>
    </div>
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-10
      • 2018-02-20
      • 2019-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-14
      相关资源
      最近更新 更多