简体   繁体   中英

Angular6 ngIf creates empty element when false

I have a problem with Anguar6 and ngIf:

    <div class="card" *ngIf="pr.cat==='livres'" >
        <img src="../../assets/img/images2.jpg">
        <div class="card-body">
            <h5 class="card-title"><b><u>Titre  :</u></b>{{pr.titreD}}</h5>
            <p class="card-text"><b><u>Description :</u></b>{{pr.description}}</p>
            <br><b><u>The donor :</u></b>{{pr.titre}}. {{pr.prenom}}  {{pr.nom}}<br>
            <b><u>Email :</u> </b>{{pr.email}}<br>
           <b><u>Téléphone: </u></b> {{pr.number}}<br>
            <a href="#" class="btn btn-primary">Click to view</a>
            <button type="submit" (click)="deleteproduit(i)" class="btn btn-primary">Supprimer</button>
        </div>
    </div>
</div>
The problem is, that angular creates an empty bloc with this comment in it:

[inspect element]

Following is the error screenshot.

错误截图

I don't think it is creating an empty element. the div you see is the outer div. your div with class="card" is not showing up.

This is part of the Angular compiler.

ngIf internally gets expanded to::

<ng-template [ngIf]="someCondition"></ng-template>

Angular wraps the host element inside <ng-template> and consumes the <ng-template> in the finished DOM by replacing it with diagnostic comments.

So, what you are seeing is of the outer div and you are seeing your ngIf block just as a comment(not creating new empty element actually).

Hope, this helps:)

* ngIf is a structural directive that shall control DOM manipulation. If your condition is false, then that element (div in this case) shall not be rendered at all.

Placing comments is a default behaviour of angular compiler. Why it places comments? This way angular knows where embedded view will be placed in DOM.

In your code the div you are seeing is the outer div, the div you have *ngIf is not rendered.

Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM