Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

277
Views
Aplique una condición usando ngFor y ngIf en angular 2

Hola, he estado tratando de filtrar una matriz con cierto éxito usando ngIF y ngFor.

 <button *ngFor="let item of items"> <div *ngIf="(item.data.type == 1)"> {{item.data.name}} </div> </button>

Este código solo muestra botones con nombre para datos que tienen tipo = 1, pero también crea botones vacíos para cada entrada de datos que no tiene tipo = 1, no puedo entender cómo deshacerme de los botones vacíos. Cualquier ayuda es muy apreciada.

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Cambiaría tu button y div :

 <div *ngFor="let item of items"> <button *ngIf="(item.data.type == 1)">{{item.data.name}}</button> </div>

De esta forma, solo se crean botones para elementos válidos.

Si los <div> no son deseables, use <ng-container> en su lugar.

Aunque no es aconsejable por motivos de rendimiento, también puede utilizar una función en su componente:

 <button *ngFor="let item of filterItemsOfType('1')">{{item.data.name}}</button>

Donde su componente tiene una función:

 filterItemsOfType(type){ return this.items.filter(x => x.data.type == type); }

Si bien esto funciona, no se recomienda y debe evitarse en la medida de lo posible.

about 4 years ago · Santiago Trujillo Report

0

Puedes crear tu propia tubería. Esa es una mejor solución.

 @Pipe({ name: 'somepipe', }) export class SomePipe { transform(objects: any[]): any[] { if(objects) { return objects.filter(object => { return object.data.type === 1; }); } } }

y usarlo en html de esta manera:

 <button *ngFor="let item of items | somepipe"> <div> {{item.data.name}} </div> </button>
about 4 years ago · Santiago Trujillo Report

0

<button *ngFor="let item of getItems()">...</button>

 getItems() { return this.items.filter((item) => item.data.type === 1); }

donde this.items es su conjunto de elementos en algún lugar por encima de esta función.

Mira esto

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!