【问题标题】:How to pass different template variables to one button in angular2?如何将不同的模板变量传递给angular2中的一个按钮?
【发布时间】:2018-09-04 07:25:00
【问题描述】:

我的组件中有两个以上的模板变量,就像吹一样:

<div #div1>
    <div #part1 [hidden]="true">
    </div>
    <div #part2>
    </div>
</div>
<div #div2>
    <div #part3 [hidden]="true">
    </div>
    <div #part4>
    </div>
 </div>
<button (click)="showDiv(div1,div2)"></button>

我想点击按钮显示part1和隐藏part2,和part3和part4一样,但是只是一个按钮,我现在能做的就是用part1和part2替换div1和div2,那么part3和part4呢?另一个按钮?但真正的要求是超过两个 div,可能是十几个,所以,有人可以帮忙吗?非常感谢。

【问题讨论】:

  • 你能分享一些你正在使用的 JavaScript 代码吗?
  • 最重要的是如何获取我点击的当前div的引用?
  • 您可以传递一个参数(例如 showDiv('1')),说明您要显示哪组 div。

标签: angular angular2-template template-variables


【解决方案1】:

要解决您的问题,您可以使用ngContainerngTemplate

使用ngContainerngTemplate

HTML:

<div> <!-- Div 1 -->
  <ng-container *ngIf="isPartVisible(1); then part1; else part2"></ng-container> 
  <ng-template #part1><div>Part 1</div></ng-template>
  <ng-template #part2><div>Part 2</div></ng-template>
</div>
<!-- Other parts here. -->

JavaScript:

var partVisibilities = {};
partVisibilities["1"] = true;

public isPartVisible(part) {
    return partVisiblities[part] == true; 
    // If you haven't set the visibility setting for a part yet, then it will not show as undefined is falsy in JS.
}

【讨论】:

    【解决方案2】:

    在你的组件中,你可以添加类似这样的东西

    `

    constructor(private renderer: Renderer2, private el: ElementRef) {}
    showDiv(){
    this.renderer.setStyle(
        this.el.nativeElement,
        'display:None',
        'block'
      );
    }
    

    `

    【讨论】:

    • 这不是“棱角分明的风格”。只需使用变量并使用 *ngIf="variable"
    • 那如何获取我点击的当前div的引用呢?
    猜你喜欢
    • 2017-06-22
    • 1970-01-01
    • 2017-11-09
    • 2017-11-10
    • 2016-09-26
    • 1970-01-01
    • 2015-06-22
    • 2014-11-30
    • 1970-01-01
    相关资源
    最近更新 更多