【问题标题】:Angular 2 load child component on click点击时Angular 2加载子组件
【发布时间】:2017-05-03 12:42:01
【问题描述】:

单击父模板中的按钮时是否可以加载子组件?例如,父模板 html 如下所示:

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

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

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

【问题讨论】:

    标签: angular


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      在你的父组件.ts中

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

      【讨论】:

        【解决方案3】:

        你可以使用也许是最基本的指令ngIf

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

        在你的组件中

        loadMyChildComponent(){
         loaded=true;
        }
        

        【讨论】:

          【解决方案4】:
          <button (click)="loadMyChildComponent()">Load</button>
          <div [hidden]="hide">
          <my-child-component></my-child-component>
          </div>
          

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

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

          【讨论】:

          • 这不只是加载然后隐藏组件吗?我不想在点击按钮之前加载它
          • 在加载父项时单击按钮而不是加载 chlid 后将如何加载
          • @masterfan 它不会加载你的组件。您可以在ngOnInit() 进行控制台登录并检查。
          【解决方案5】:

          你可以使用角度指令*ngIf

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

          在你的 component.js 中

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-10-16
            • 1970-01-01
            • 2017-11-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-07-13
            相关资源
            最近更新 更多