2017-07-17 49 views
-1

<div>将模板的HTML英雄细节内容包装起来。然后添加ngIf内置指令并将其设置为组件的selectedHero属性。ngIf对Angular Heroes教程没有价值

<div *ngIf="selectedHero"> 
    <h2>{{selectedHero.name}} details!</h2> 
    <div><label>id: </label>{{selectedHero.id}}</div> 
    <div> 
    <label>name: </label> 
    <input [(ngModel)]="selectedHero.name" placeholder="name"/> 
</div> 

该应用程序不再失败和名称列表在浏览器中再次显示。

事实是,没有ngIf指令,应用程序永远不会失败。为了测试这一点,我清空了输入表单,这反过来清空了绑定的列表项,但无论是否包含ngIf,都不会发生任何奇怪的事情。

任何解释?

+0

您确定控制台中没有错误吗?因为'selectedHero.name'应该会失败,如果'selectedHero'未定义或为空。 –

+0

@MikeMcCaughan零错误 – usefulBee

+2

然后我想这是教程中的一个错误。你应该告诉Angular团队...... –

回答

1

该演示似乎失败了我使用this example,模板导致错误,因为该模型是未定义的。

TypeError: Cannot read property 'name' of undefined

的ngIf指令通过如果模型不可省略元件防止这些错误。

+1

对我来说也是失败的[PLNKR上的DEMO](https://plnkr.co/edit/AaFcdmNFyyslCNYcqZcG?p=preview)。 – georgeawg

0

关键是在这一点上作为tutorial解释说:

所以用这个简单 selectedHero财产更换英雄属性

然而,使用nglf是不是唯一因为即使使用空值来初始化所选属性也足以防止相关错误,这使得ngif指令显得无用:

export class AppComponent { 
    selectedHero: Hero = { 
    id: null, 
    name: null 
}; 
}