首页 文章

单击Angular 2加载子组件

提问于
浏览
8

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

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

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

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

5 回答

  • 2

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

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

    在您的组件中

    loadMyChildComponent(){
     loaded=true;
    }
    
  • 3

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

    <button (click)="loadMyChildComponent();">Load</button>
    <my-child-component *ngIf="loadComponent"></my-child-component>
    
    loadMyChildComponent() {
      loadComponent = true;
      ...
    }
    
  • 0

    利用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
    <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;
        }
    
  • 11

    你可以使用angular指令*ngIf

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

    在你的component.js中

    public childComponentLoaded: boolean = false;
    loadChildComponent() {
        this.childComponentLoaded = true
    }
    

相关问题