A Coder
A Coder

Reputation: 3046

Angular 6 *ngFor

I have 2 set of code in which one work and other doesn't. I need to know why?

Not Working:

<p *ngFor="let recp of recipes">
<div class="row">
    <div class="col-xs-12">
        <a href="#" class="list-group-item clearfix">
            <div class="pull-left">
                <h4 class="list-group-item-heading">{{recp.name}}</h4>
                <p class="list-group-item-text">{{recp.description}}</p>
            </div>
            <span class="pull-right">
                <img src="{{recp.imagePath}}" alt="" class="img-responsive" style="max-height:50px;">
            </span>
        </a>
        <app-recipe-item></app-recipe-item>
    </div>
</div>

Error: Cannot read property 'name'of undefined.

Working:

<div class="row">
    <div class="col-xs-12">
        <a href="#" class="list-group-item clearfix" 
        *ngFor="let recp of recipes">
            <div class="pull-left">
                <h4 class="list-group-item-heading">{{recp.name}}</h4>
                <p class="list-group-item-text">{{recp.description}}</p>
            </div>
            <span class="pull-right">
                <img src="{{recp.imagePath}}" alt="" class="img-responsive" style="max-height:50px;">
            </span>
        </a>
        <app-recipe-item></app-recipe-item>
    </div>
</div>

But this works if you think the issue is with the <p> tag,

<p *ngFor ="let arr of addIncrement;>{{arr}}</p>

Upvotes: 0

Views: 1225

Answers (2)

Chellappan வ
Chellappan வ

Reputation: 27293

According to MDN, only phrasing content is allowed within a

element. Angular might be enforcing that rule more than your browser

P elements are only allowed to contain inline elements

Check this for more Info:

World Wide Web Consortium (W3C) https://www.w3.org/TR/html401/struct/text.html#h-9.3.1

The P element represents a paragraph. It cannot contain block-level elements (including P itself).

<!ELEMENT P - O (%inline;)*            -- paragraph -->

Upvotes: 1

David R
David R

Reputation: 15639

Please check for null (or) undefined before interpolating it. You can use the ? to in such cases like this,

<h4 class="list-group-item-heading">{{recp?.name}}</h4>
   <p class="list-group-item-text">{{recp?.description}}</p>

Hope this helps!.

Upvotes: 1

Related Questions