Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 with *ngFor and ngIf to hide first element

In Angular 2, I got a list of items and based on a given condition (i.e based on location number) I am setting the list to repeat.

I need to hide the "remove text" for the first box each location.

Plunker: https://plnkr.co/edit/xtX5BjTBjO61sD2tLwWN?p=preview:

actual img

[1]: https://plnkr.co/edit/xtX5BjTBjO61sD2tLwWN?p=preview

import {Component} from '@angular/core';

@Component({
	selector: 'app',
	template: `
	  
    <ul *ngFor="let locdata of locations">
   
     <template ngFor let-item [ngForOf]="items"; let-i=index>
          <div *ngIf="item.location==locdata.location">
             <div class="title"> location  {{ item.location}} <span  *ngIf="isNotFirst(item)">  remove </span> </div>
          <div class="container"> {{ item.sedule}}</div>
       </div>
      </template>
	  </ul>
	 
	`
})
export class App {
  items: string[];
  
   isNotFirst(item: any) {
      return this.items.filter(i => i.location === item.location).map(i => i.id).indexOf(item.id) !== 0;
    }
  
  locations:any;
  
  constructor() {
    this.locations=[{location:1},{location:2},{location:3}]; 
    
    this.items = [{
    id:1,
    location:1,
    sedule:1
  },
  {
    id:2,
    location:2,
    sedule:1
  },
  {
    id:3,
    location:1,
    sedule:2
  },
  {
    id:4,
    location:2,
    sedule:2
  },
  {
    id:5,
    location:1,
    sedule:2
  },
  {
    id:6,
    location:2,
    sedule:3
  },  {
    id:7,
    location:3,
    sedule:1
  },
  {
    id:8,
    location:3,
    sedule:2
  },
  {
    id:9,
    location:3,
    sedule:3
  }];
  }
  
}
like image 754
B.V.S Bharat Kumar Avatar asked Dec 07 '25 17:12

B.V.S Bharat Kumar


1 Answers

assume you have a <span> in *ngFor logic, you can use first from *ngFor and show/hide <span> by *ngIf

<div *ngFor="let item in data; let first=first;">
  {{item.attr}}
  <span *ngIf="!first">
    remove
  </span>
</div>

your working plunker.

like image 119
Pengyy Avatar answered Dec 09 '25 06:12

Pengyy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!