Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

275
Visualizações
Apply a condition using ngFor and ngIf in angular 2

Hi There I have been trying to filter an array with some success using ngIF and ngFor.

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

This code does only show buttons with name in it for data that has type=1 but it also create empty buttons for each data entry that doesn't have type=1, I can't figure out how to get rid of empty buttons. Any help is much appreciated.

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

I would flip-flop your button and div:

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

This way only buttons get created for valid items.

If <div>'s aren't desirable use <ng-container> instead.

Though not advisable due to performance reasons, you can also use a function in your component:

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

Where your component has a function:

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

While this works, it is not recommended and should be avoided where possible.

about 4 years ago · Santiago Trujillo Relatório

0

You can create your own pipe. That is better solution.

@Pipe({
    name: 'somepipe',
})
export class SomePipe {

    transform(objects: any[]): any[] {
        if(objects) {
            return objects.filter(object => {
                return object.data.type === 1;
            });
        }
    }

}

and use it in html in this way:

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

0

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

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

where this.items is your array of items somewhere above this function.

Check this out

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda