How to store a variable in a specific chunk of the template?

Asked

Viewed 83 times

0

I’m accessing data from an object:

<div *ngFor="let objeto of objetos">
    <div 
      [ngClass]="{'minha-classe': !!pegaDados(objeto.id).isValido}">
        {{ pegaDados(objeto.id).nome }}
    </div>
</div>

But the time and processing spent pulling data from the API with the function pegaDados() is very high. How can I store this data within one of the two <div> to use during the execution of each loop?

  • 1

    Dude, blah through the string Interpolation {{ }} you can run Javascript in Html, but this is not indicated, especially when the function is asynchronous. Html is structure and Ts is code.

  • My focus is not on the asynchronous function itself, but on how I can save the data of a generic function into a variable in the block I will work on

  • 1

    I don’t quite understand your doubt, Let object is no longer storing the data?

  • but how can I save the data returned by function pegaDados() in a variable?

  • 1

    It would be good to enter the code of the Ts of the stuck function().

  • 1

    have you tried to make a variable receive the function? Type const getData = pegarDados(), and then call at the angle with the interpolation {{ getData.nome }}?

  • @Leandrade the function returns an observable of an object interface Resposta{id: number, isValido: boolean, nome: string} as follows: pegaDados(id:number){return this.httpService.get(this.API_ADDRESS + "/" + id);}

  • @adventistaam does not apply, I am trying to save the data in the template

Show 3 more comments

1 answer

2


As the staff commented, starting this processing in the template is not the most indicated but focusing on your question directly you could do as follows:

<div *ngFor="let objeto of objetos">
    <!-- Criar um array de uma única posição c/o resultado do pegarDados() -->
    <ng-container *ngFor="let temp of [pegarDados(objeto)]">
    <div [ngClass]="{'minha-classe': !!temp.isValido}">
        {{ temp.nome }}
    </div>
</div>

It’s not an elegant solution but it would work in the context you proposed. Remember that you can initialize this processing at some point in the life cycle of your component and use for example, the async pipe to render the data in the template.

Turning to the question of the variable in the template, there is another interesting reference using directive: https://stackoverflow.com/questions/38582293/how-to-declare-a-variable-in-a-template-in-angular

Browser other questions tagged

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