【问题标题】:ngFor First and Last Instance of a Class Do ThisngFor 类的第一个和最后一个实例
【发布时间】:2017-10-20 14:24:31
【问题描述】:

我正在使用 Angular 4+。请注意: first 和 last 需要基于类实例,而不是元素。所以 ngFor 中的 let first = first 是行不通的。我目前导入了 jQuery 来处理这个问题,但想看看是否有办法不使用 jQ。

在组件ts文件中:

items: any = [{number: 0, text: 'blah blah'},{number: 0, text: 'blah blah'},{number: 1, text: 'blah blah'},{number: 1, text: 'blah blah'},{number: 1, text: 'blah blah'}, etc...

在 HTML 文件中:

<ion-row *ngFor="let item of items [ngClass]="'item-class-' + item.number">
  <ion-col>{{item.text}}</ion-col>
</ion-row>

现在我想要做的是获取一个类的第一个实例和最后一个 - 一旦我拥有它,我想设置它的样式或将一个类添加到行中。例如在 jQuery 中我会这样做:

$( 'ion-row.item-class-0' ).first().css( 'background-color', 'red' );
$( 'ion-row.item-class-1' ).first().css( 'background-color', 'red' );

【问题讨论】:

    标签: angular ngfor angular-ng-class


    【解决方案1】:

    更新答案:

    模板:

    <ion-row *ngFor="let item of items" [ngClass]="'item-class-' + item.number">
        <ion-col>{{item.text}}</ion-col>
      </ion-row>
    

    component.ts

    import { Component, AfterViewInit } from '@angular/core';
    import * as $ from 'jquery';
    
    @Component({...})
    export class HomePage {
    
        items: any = [{
            number: 0,
            text: 'blah blah'
        }, {
            number: 0,
            text: 'blah blah'
        }, {
            number: 1,
            text: 'blah blah'
        }, {
            number: 1,
            text: 'blah blah'
        }, {
            number: 1,
            text: 'blah blah'
        }];
    
        ngAfterViewInit() {
            $( 'ion-row.item-class-0').first().css( 'background-color', 'red' );
            $( 'ion-row.item-class-1').last().css( 'background-color', 'red' );
        }
    }
    

    它会为我工作试试这个:

    【讨论】:

    • first 和 last 需要基于类实例,而不是元素。
    • 在这个 jquery 方法中它将被声明在哪里? ngOnit 还是构造函数??
    • 在类 ngAfterViewInit()
    • @RooksStrife 我刚刚更新了答案,可以这样检查和尝试吗?如果它在您的项目中不起作用,请检查您的 jquery 是否安装正确或工作
    • 谢谢,我有这个。如果可能的话,我试图在不使用 jQuery 的情况下以 Angular 的方式做到这一点。如果没有,我会坚持使用 jQ。
    猜你喜欢
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多