【问题标题】:Binding property to an element's child using element's name | Angular 5使用元素名称将属性绑定到元素的子元素 |角 5
【发布时间】:2018-10-21 19:08:31
【问题描述】:

我正在使用 Angular 5 构建应用程序。我被困在需要将属性绑定到变量(元素名称)的位置。下面提供的代码正在运行,但我确信这不是正确的方法,还有另一种方法。

案例:父容器内部有箭头填充(.arrow-fill)和箭头边框(.arrow-border)。单击容器时,我需要根据某些条件隐藏/显示箭头。

现在,我已经使用“#”为父级命名,并将其传递给在 typescript 中创建的方法。并根据条件为元素(的名称)分配一个新属性。 下面是我所做的示例代码。有多个这样的选项卡,它们是硬编码的,不使用 ngFor 生成它们。

<li #liTab2 (click)="checkAndDisplay(liTab1)">
<div class="arr arrow-border" *ngIf="liTab.showBorder"></div>
<div class="arr arrow-fill" *ngIf="!liTab.showBorder"></div>
</li>

<li #liTab2 (click)="checkAndDisplay(liTab2)">
<div class="arr arrow-border" *ngIf="liTab2.showBorder"></div>
<div class="arr arrow-fill" *ngIf="!liTab2.showBorder"></div>
</li>

现在在打字稿中,函数是:
checkAndDisplay(elem) { elem.nativeElement.showBorder = !elem.nativeElement.showBorder; /*some other functions are also taking place here */ }

有没有其他方法,正确的方法,在这里做到这一点。

【问题讨论】:

    标签: angular data-binding binding angular5


    【解决方案1】:
    <ul>
        <li (click)="showBorder = !showBorder">
            <div class="arr arrow-border" *ngIf="showBorder">Div 1</div>
            <div class="arr arrow-fill" *ngIf="!showBorder">Div 2</div>
        </li>
    </ul>
    

    这是另一种方法!

    【讨论】:

    • 我有多个 li 标签,而且我需要调用一个方法,因为它正在做很多事情。所以你能建议任何其他答案吗?谢谢
    • 所以你必须使用 *ngFor 基于你的数组的多个 li 标签。 &lt;ul&gt; &lt;li *ngFor="let obj of YourData" (click)="obj.showBorder = !obj.showBorder"&gt; &lt;div class="arr arrow-border" *ngIf="obj.showBorder"&gt;Div 1&lt;/div&gt; &lt;div class="arr arrow-fill" *ngIf="!obj.showBorder"&gt;Div 2&lt;/div&gt; &lt;/li&gt; &lt;/ul&gt;
    • 是的,你是对的。我已经用新代码更新了我的问题。但是如果我将使用 ngFor 重复,并且单击任何 li 标记,则 showBorder 的值会发生变化,并且会影响所有其他 li 的值。我们可以将其限制为特定的 li 标签吗?
    • 你可以使用这个代码&lt;ul&gt; &lt;ng-template *ngFor="let obj of YourData"&gt; &lt;li *ngIf="your-true-condition" (click)="obj.showBorder = !obj.showBorder"&gt; &lt;div class="arr arrow-border" *ngIf="obj.showBorder"&gt;Div 1&lt;/div&gt; &lt;div class="arr arrow-fill" *ngIf="!obj.showBorder"&gt;Div 2&lt;/div&gt; &lt;/li&gt; &lt;li *ngIf="your-false-condition"&gt; &lt;div class="arr arrow-border" *ngIf="obj.showBorder"&gt;Div 1&lt;/div&gt; &lt;div class="arr arrow-fill" *ngIf="!obj.showBorder"&gt;Div 2&lt;/div&gt; &lt;/li&gt; &lt;/ng-template&gt; &lt;/ul&gt;
    • 好的。它有效,可能不是我想要的。但是将新的键值分配给不存在的对象是否是一种好方法?
    猜你喜欢
    • 2013-11-05
    • 2023-01-15
    • 1970-01-01
    • 2018-06-04
    • 2015-04-13
    • 2013-05-31
    • 2013-10-28
    • 1970-01-01
    • 2017-07-20
    相关资源
    最近更新 更多