如何在运行时在根组件中更改Angular组件

时间:2019-04-15 07:30:58

标签: angular typescript angular-components

我想添加一个动态表格。按下配置按钮后,表格应从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 {

}

2 个答案:

答案 0 :(得分:1)

您可以尝试:

<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>


答案 1 :(得分:0)

类似

<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;
}