【问题标题】:Add border to the div that was clicked为被点击的 div 添加边框
【发布时间】:2020-07-18 10:25:04
【问题描述】:

我有一个对象可以用来存储一些信息。 为了呈现这些数据,我使用 * ngFor 为每个实例创建一行。

当我点击其中一条线时,有没有办法添加边框?边框应该只添加到被点击的那一行,如果点击另一行后,边框从上一行消失,出现在当前行。

我该怎么做?

Demo

.html

<div *ngFor="let item of objects; let i = index" style="width: 100%;">
    <div class="d-flex flex-row divs">
        <div>
            <span>{{item.id}}</span>
        </div>
        <div>
            <div>
                <span>{{item.name}}</span>
            </div>
        </div>
        <div style="margin-left:auto">
            <button>click</button>
        </div>
    </div>
</div>

【问题讨论】:

    标签: html css angular typescript bootstrap-4


    【解决方案1】:

    您可以使用ngClass根据您点击的项目动态设置类。

    例如:

    <div class="d-flex flex-row divs" 
        [ngClass]="{'active' : (selectedItem.id === item.id)}"> <div>
      ...
    
    </div> 
    

    然后在单击按钮时,您可以传递被点击的项目:

    <div style="margin-left:auto">
                <button (click)="setItem(item)">click</button>
            </div>
    

    component.ts 文件中你可以设置选中项如下:

    public selectedItem :any = {};
    
    setItem(item){
      this.selectedItem = item
    }
    

    现在在 css 中你可以有 .active class css 如下:

    .active{
      border : 1px solid red;
    }
    

    这是工作示例:demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-31
      • 1970-01-01
      • 2022-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-04
      • 1970-01-01
      相关资源
      最近更新 更多