What is the behavior of ngfor and ngif?


I created a accordion list . This accordion list I believe from a json obtained from a post query.

When I have the answer json, I create the accordion list . I create the first level of the accordion but when deploying it, depending on a value, I show an image or not.

Whether or not I show the image by evaluating a property of a variable. In addition to displaying the image, I call a method that simply calls an alert.

My problem is that the image does show me only once but the alert shows it to me several times ...

My code is as follows:

<label *ngFor="let variable of placa.variablesplaca;" no-padding>

    <div *ngIf="variable.magnitud.magnitud === 'final de carrera' && variable.senyal.orden === 1 && variable.valor === 1; else second">  
        <img src="../../assets/imgs/compuertaabierta.png" style="width: 12vh; height: 20vh"><br>
          {{ alertar('Abierta') }}

    <div #second *ngIf="variable.magnitud.magnitud === 'final de carrera' && variable.senyal.orden == 2 && variable.valor == 1; else third">
        <img src="../../assets/imgs/compuertacerrada.png" style="width: 12vh; height: 20vh"><br>
          {{ alertar('Cerrada') }}

    <div #third *ngIf="variable.magnitud.magnitud === 'final de carrera' && variable.valor == 0">
        <img src="../../assets/imgs/compuertasemi.png" style="width: 12vh; height: 20vh"><br>
          {{ alertar('Semi') }}

In the response of the json I have several "variables" but only 2 whose magnitude is "end of career" with which, I should only enter 2 times the if but what I see is the following, it shows me 2 times the image, that's perfect, but it shows me the warning many times.

I do not know if I have explained it well, I can explain my case more if it is appropriate or not well understood.

asked by Pablo Simon DiEstefano 29.05.2018 в 12:18

1 answer


The life cycle of the Angular components causes a component to redraw several times, especially if you are testing in "development mode", where each check is made twice to check that there are no undesirable effects that can cause a infinite loop of changes.

That will make that *ngFor run at least twice, maybe 4, when loading the component, showing the number of alerts in duplicate or quadrupled

answered by 29.05.2018 в 12:34