【问题标题】:ngClass toggle particular element only while using ngFor Angular5ngClass 仅在使用 ngFor Angular5 时切换特定元素
【发布时间】:2019-02-06 11:24:09
【问题描述】:

我想在单击单击事件时切换特定元素,并且它在循环中切换所有类,意味着所有 div 显示。这是我的代码

<div *ngFor="let xyz of abc">
    <span (click)="showOptions = !showOptions"></span>
    <ul [ngClass]="{show:showOptions}">
        <li> some text</li>
    </ul>
    <div>{{xyz}}</div>
</div>

它应该打开下一个元素而不是全部! 有什么帮助吗?

【问题讨论】:

    标签: angular angular5 ngfor ng-class


    【解决方案1】:

    发生这种情况是因为您为每个 ngFor 循环元素使用了一个布尔值。您应该尝试在数组元素中添加一个布尔字段:

    abc = [
        {
            text: 'el1',
            show: false
        },
        {
            text: 'el2',
            show: false
        },
        {
            text: 'el3',
            show: false
        },
    ]
    

    在您的模板中:

    <div *ngFor="let xyz of abc">
        <span (click)="xyz.show = !xyz.show"></span>
        <ul [ngClass]="{show:xyz.show}">
            <li>{{xyz.text}}</li>
        </ul>
    </div>
    

    注意

    您也可以使用ngIf 来显示/隐藏您的选项列表:

    <ul *ngIf="xyz.show">
    

    【讨论】:

    • @Augustine,我不能在对象元素中添加“show: false”,这将是典型的添加,因为这堆对象层次结构很重,可能有数千个!!任何其他想法
    • 对不起,我不明白你的评论。在 subscribe 函数中,可以使用 for 循环轻松添加该字段。据我所知,没有其他简单的方法可以做到这一点。
    猜你喜欢
    • 2018-10-24
    • 2020-10-23
    • 2019-02-14
    • 1970-01-01
    • 2018-04-30
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    相关资源
    最近更新 更多