Angular 6 *ngFor

Angular 6 *ngFor

我有两套代码,一套有效,另一套无效。我需要知道为什么?

不工作:

<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>

错误:无法读取 属性 未定义的“名称”。

工作:

<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>

但是,如果您认为问题出在 <p> 标签上,则此方法有效,

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

请在插入前检查 null(或)undefined。在这种情况下,您可以使用 ?

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

希望对您有所帮助!

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

检查此以获取更多信息:

万维网联盟 (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 -->