【问题标题】:How can I make the first item in my *ngFor active by default (i.e. border-color of active item should be differnt from other items by deafult)默认情况下,如何使我的 *ngFor 中的第一个项目处于活动状态(即活动项目的边框颜色应该与默认情况下的其他项目不同)
【发布时间】:2021-01-03 10:58:34
【问题描述】:

目前,我正在开发 Angular 8 应用程序。我想 默认情况下使我的第一项循环处于活动状态。从某种意义上说,它是活跃的 边框颜色变了。为了进一步澄清我的问题,我还 附上一张图片。在下图中,您可以看到第一个 类别是“鸡”。所以必须默认选中。任何帮助将不胜感激。 谢谢!

我的 HTML

        <div class="category-slider swiper-container">
          <div class="swiper-wrapper">
            <div class="swiper-slide" style="margin-right: 100px;" *ngFor="let i = index; let category of brand_Categories">
              <a href="javascript:void(0);" (click)="getSubCategories(category.CategoryId,category?.CategoryTitle)"
                 class="categories">
                 <div>
                <div class="icon text-custom-white bg-light-green" id="myDIV" (click)="toggle(i)" [ngClass]="(selectedID == i) ? 'selected' : 'not-selected' ">

                      <img
                      src="{{category?.CategoryImage || 'https://giftclubimagestorage.blob.core.windows.net/images/biryani.jpg'}}"
                      class="rounded-circle"
                      alt="{{category?.CategoryTitle || ''}}" class="imgrr">

                </div>
              </div>
                <span class="text-light-black cat-name">{{category?.CategoryTitle || ''}}</span>
              </a>
            </div>
          </div>

【问题讨论】:

  • 您好,您可以尝试在 ngOninit() 中将 selectedID 设置为 0
  • 我试过了,但它不起作用。也许您可以通过代码详细说明
  • 哦,谢谢,伙计。有效。我的错,我之前犯了一个错误。

标签: javascript html angular typescript angular8


【解决方案1】:

使用 *ngFor 上下文中提供的first 变量怎么样?

<div *ngFor="let category of brand_Categories; let i = index; let first = first">
  <div [ngClass]="(selectedID == i || !selectedID && first) ? 'selected' : 'not-selected' ">
</div>

可选

<div *ngFor="let category of brand_Categories; let i = index;>
  <div [ngClass]="(selectedID == i || !selectedID && i == 0) ? 'selected' : 'not-selected' ">
</div>

另外考虑在组件中将selectedId 设置为零。

【讨论】:

    【解决方案2】:

    这是我试过的一个例子。

    html

    <div fxLayout="row" fxLayoutGap="20px">
      <div *ngFor="let item of items; let i = index;">
        <div class="item" [ngClass]="{'selected-item': selectedID == i}" (click)="selectItem(i)">{{item}}</div>
      </div>
    </div>
    

    css

    .item {
        padding: 10px;
        border: solid 1px grey;
    }
    .selected-item {
        border: solid 2px green;
    }
    

    ts

    public items = ['Item1', 'Item2', 'Item3', 'Item4'];
    public selectedID = 0;
    
    selectItem(i){
      this.selectedID = i;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-23
      • 2017-07-09
      • 1970-01-01
      • 1970-01-01
      • 2014-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多