对于类的第一个和最后一个实例执行此操作

时间:2017-10-20 14:24:31

标签: angular ngfor angular-ng-class

我正在使用Angular 4+。请注意:第一个和最后一个需要基于类实例,而不是元素。所以在ngFor中让第一个=第一个不起作用。我目前导入了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' );

1 个答案:

答案 0 :(得分:0)

更新回答:

模板:

<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' );
    }
}

enter image description here

它会为我工作试试这个: