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

284
Visualizações
Use ngFor for showing data in two different places from same Array Angular

I have a single array whose data I need to display at two different sections using *ngFor. Like I have two sections: Section 1 and Section 2. From the below array I need to display keys having values section1 inside the first tag and those having values as section2 inside the second tag. I have tried a lot but not able to do so, considerably new with Angular. Please help! Note: I cannot use two different variables and then filter it out in ts file and then use those 2 variables inside my *ngFor.

arr=[{age:"29",data1:"section1"},{age:"30",data1:"section2"},{age:"22",data1:"section1"},{age:"32",data1:"section2"}]

HTML Code: 
<div *ngFor="let data of arr;">
<p>Section 1</p>
<h1>{{data.age}}</h1>

<p>Section 2</p>
<h1>{{data.age}}</h1>
</div>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The easy way if make two *ngFor. You can use *ngTemplateOutlet if you can not "repeat" the "inner html"

<div>Section 1</div>
<div *ngFor="let item of arr">
  <ng-container *ngIf="item.data1 == 'section1'">
    <ng-container
      *ngTemplateOutlet="template; context: { $implicit: item }"
    ></ng-container>
  </ng-container>
</div>
<div>Section 2</div>
<div *ngFor="let item of arr">
  <ng-container *ngIf="item.data1 == 'section2'">
    <ng-container
      *ngTemplateOutlet="template; context: { $implicit: item }"
    ></ng-container>
  </ng-container>
</div>
<ng-template #template let-item>
  {{ item | json }}
</ng-template>

If you only want an unique loop you need "play" with css flex order

<div class="wrapper">
  <div [style.order]="0">Section 1</div>
  <div [style.order]="1000">Section 2</div>
  <div
    *ngFor="let item of arr; let i = index"
    [style.order]="item.data1 == 'section2' ? 1000 + i : 1 + i"
  >
    {{ item | json }}
  </div>
</div>

where

.wrapper{
  display:flex;
  flex-direction: column;
}

You can see the two approach in this stackbliz

about 4 years ago · Juan Pablo Isaza Relatório

0

You can try like below.

component.ts

import { Component, OnInit, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  name = 'Angular ' + VERSION.major;
  arr = [
    { age: '29', data1: 'section1' },
    { age: '30', data1: 'section2' },
    { age: '22', data1: 'section1' },
    { age: '32', data1: 'section2' },
  ];

  sortedData;

  constructor() {}

  ngOnInit() {
    this.sortedData = this.arr.reduce((acc, curr) => {
      if (acc.hasOwnProperty(curr.data1)) {
        acc[curr.data1].push(curr);
        return acc;
      }

      acc[curr.data1] = [curr];
      return acc;
    }, {});
  }

}

component.html

<div *ngFor="let item of sortedData | keyValue">
  <h2>{{ item.key }}</h2>

  <div *ngFor="let obj of item.value">{{ obj.age }}</div>
</div>

key-value pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'keyValue',
})
export class KeyValuePipe implements PipeTransform {
  transform(input: any): any {
    let keys = [];
    for (let key in input) {
      if (input.hasOwnProperty(key)) {
        keys.push({ key: key, value: input[key] });
      }
    }
    return keys;
  }
}

Updated code.

Working Demo

Let me know if you have any issue.

about 4 years ago · Juan Pablo Isaza 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