单击Angular 2加载子组件

时间:2017-05-03 12:42:01

标签: angular

单击父模板中的按钮是否可以加载子组件?例如,父模板html看起来像:

<button (click)="loadMyChildComponent();">Load</button>
<my-child-component></my-child-component>

我想这样做的原因是因为my-child-component需要一些时间来加载它会减慢一切。因此,我只想在用户点击加载时加载它。我无法更改父模板结构。它必须在那里。

我只想在点击加载按钮时输入子组件的ngOnInit。

5 个答案:

答案 0 :(得分:17)

您可以将* ngIf指令用于父级的初始化组件,因此您的代码将是这样的

<button (click)="loadMyChildComponent();">Load</button>
<my-child-component *ngIf="loadComponent"></my-child-component>

loadMyChildComponent() {
  loadComponent = true;
  ...
}

答案 1 :(得分:4)

利用flag来控制子组件的负载。

<button (click)="loadMyChildComponent();">Load</button>
<div *ngIf= 'loadComponent'>
<my-child-component></my-child-component>
</div>

在您的父组件.ts

 private loadComponent = false;
    loadMyChildComponent(){
       this.loadComponent = true;
    }

答案 2 :(得分:2)

您可以使用最基本的指令ngIf

<button (click)="loadMyChildComponent();">Load</button>
<my-child-component *ngIf="loaded"></my-child-component>

在您的组件中

loadMyChildComponent(){
 loaded=true;
}

答案 3 :(得分:2)

<button (click)="loadMyChildComponent()">Load</button>
<div [hidden]="hide">
<my-child-component></my-child-component>
</div>

在父类中声明varible hide并创建一个函数loadMyChildComponent

 public hide = true;
  loadMyChildComponent(){
       this.hide= true;
    }

答案 4 :(得分:0)

您可以使用角度指令*ngIf

<button (click)="loadChildComponent();">Load Child Component</button> <child-component *ngIf="childComponentLoaded"></child-component>

在您的component.js中

public childComponentLoaded: boolean = false;
loadChildComponent() {
    this.childComponentLoaded = true
}
相关问题