Sort Angular Component List

Asked

Viewed 274 times

1

This is Galera speaking! My question is this::

  • imagine a DIV that within it there are several components like the example below:
<div class="row">
      <app-fogao></app-fogao>
    
        <app-geladeira></app-geladeira>
    
        <app-notebook></app-notebook>
    
        <app-ar-condicionado></app-ar-condicionado>
    
        <app-televisao></app-televisao>
    
        <app-celular></app-celular>
    
        <app-maquina-lavar></app-maquina-lavar>
    
    </div>

And then I want to order the display of these components according to the order I receive from the backend, something like below:

    let ordemProdutos = [
      {produto: 'fogao' , posicao: 3},
      {produto: 'geladeira' , posicao: 5},
      {produto: 'notebook' , posicao: 1},
      {produto: 'ar-condicionado' , posicao: 4},
      {produto: 'televisao' , posicao: 2},
      {produto: 'celular' , posicao: 7},
      {produto: 'maquina-lavar' , posicao: 6}
    ];

And then the display of the components that initially would be equal to section 01, was changed to be equal to the section below (according to the order received above):

<div class="row">
  <app-notebook></app-notebook>

  <app-televisao></app-televisao>
  
  <app-fogao></app-fogao>
  
  <app-ar-condicionado></app-ar-condicionado>
  
  <app-geladeira></app-geladeira>

  <app-maquina-lavar></app-maquina-lavar>
  
  <app-celular></app-celular>

    </div>

Does anyone have any idea how to dynamically sort the components?

NOTE: This is a way to demonstrate the problem I have. the real components do not have these names. I couldn’t create a generic component because each one of them is completely different in terms of content and structure. They are displayed side by side and I need to create a way to sort them according to the positioning that each component has recorded in the backend.

1 answer

1

The best would be to first order your list

ordemProdutosOrdenada = ordemProdutos.sort((a,b)=> a.posicao - b.posicao)

ai vc can use ngComponentOutlet inside an ngfor to dynamically instate its components

<ng-container *ngComponentOutlet="produto.produto"></ng-container>
  • Thank you so much for your help! I was able to do exactly your example. I will go deeper into this subject. I created a little project on Github and Stackblitz If you want to take a look at the link below: - https://stackblitz.com/edit/angular-ivy-wkcdsr?file=src/app/app.component. -https:///hubgit.com/MatiasNeto/ComponentDinamico

Browser other questions tagged

You are not signed in. Login or sign up in order to post.