【问题标题】:Angular 2 Hide child componenets on clickAngular 2点击时隐藏子组件
【发布时间】:2017-05-03 11:02:03
【问题描述】:

我想在单击某个单选按钮时隐藏整个组件。 子节点选择器是:app-node-details-full 和 app-node-tree-diagram。这是我的父模板代码:

<div class="displaySwitch">
  <input (click)="fullview.hidden = !fullview.hidden" checked type="radio" name="displayType" value="diagram"> Full View
  <input (click)="diagram.hidden = !diagram.hidden" type="radio" name="displayType" value="fullview"> Diagram
</div>

这些是带有(单击)附加到它们的单选按钮

现在在其他 div 我有我的子组件:

  <div class="nodeDetails" [ngStyle]="nodeDetailsStyle">
    <app-node-details-full #fullview</app-node-details-full>
    <app-node-tree-diagram #diagram></app-node-tree-diagram>
  </div>

如果这对您有意义的话,两个 div 都包含在一个主目录中。我究竟做错了什么?每次单击单选按钮时都会出现异常

o.diagram 未定义

o.fullview 未定义

【问题讨论】:

    标签: angular


    【解决方案1】:

    问题是你不能从模板内部设置变量

    你有以下行:

    (click)="fullview.hidden = !fullview.hidden"
    

    您需要将其提取到方法中

    hide(){
        fullview.hidden = !fullview.hidden
    }
    

    然后在点击时触发这个方法:

    (click)="hide()"
    

    编辑:

    我注意到您实际上是在尝试设置模板变量。

    模板变量只存在于模板中,你不能通过JS访问它们(因为它们被编译成HTML)为了访问它们你需要使用@ViewChild

    虽然我不推荐这种方法。

    改为 - 我会使用组件变量和ngIf

    来控制可见性

    【讨论】:

      【解决方案2】:

      你得到undefined,因为我认为你有你的变量#fullview#diagram在你试图使用变量的单选按钮之后定义。我认为您最好使用私有变量并捕获所选单选按钮的值。然后使用*ngIf 关闭。

      例子:

      checkboxValue: string;
      
      <div class="displaySwitch">
        <input checked type="radio" name="displayType" [(ngModel)]="checkboxValue" value="fullView"> Full View
        <input type="radio" name="displayType" [(ngModel)]="checkboxValue" value="diagram"> Diagram
      </div>
      
      <div class="nodeDetails" [ngStyle]="nodeDetailsStyle">
        <app-node-details-full *ngIf="checkboxValue == 'fullView'"</app-node-details-full>
        <app-node-tree-diagram *ngIf="checkboxValue == 'diagram"></app-node-tree-diagram>
      </div>
      

      【讨论】:

        【解决方案3】:
        *ngIf="myVar"
        

        [hidden]="!myVar"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-07-09
          • 2017-11-01
          • 2017-04-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-13
          相关资源
          最近更新 更多