【发布时间】:2016-03-27 11:09:32
【问题描述】:
在 angular2 模板中访问连字符属性时如何使用 elvis 运算符
http://plnkr.co/edit/z3Wqn7EScgxcAhrFJWjv?p=preview
//our root app component
import {Component} from 'angular2/core'
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<h2>Hello {{name}}</h2>
{{asyncObj1?.theprop}}
{{asyncObj2?['the-prop']}} <!-- this throws error -->
</div>
`,
directives: []
})
export class App {
constructor() {
setTimeout(function(){
this.asyncObj1 = {
'theprop': 'value'
}
this.asyncObj2 = {
'the-prop': 'async value'
}
}, 2000)
}
}
【问题讨论】:
-
你需要一个 ngIf。类似
<div *ngIf="asyncObj2">{{asyncObj2['the-prop']}}</div> -
或
<template [ngIf]="asyncObj2"> {{asyncObj2['the-prop']}} </template>,不会留下任何额外的标记,即 -div wrapper。