【发布时间】:2017-07-12 20:53:25
【问题描述】:
我正在使用一个返回布尔值的函数,以使用 ngFor 循环内的 hidden 属性设置项目的可见性。
const countries = [
{country: 'USA', hide: 'false'},
{country: 'UK', hide: 'false'},
{country: 'Germany', hide: 'true'},
{country: 'France', hide: 'true'},
{country: 'Japan', hide: 'false'},
{country: 'Russia', hide: 'false'}
]
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
<my-list></my-list>
`,
})
export class App {
name:string;
constructor() {
this.name = `Angular! v${VERSION.full}`
}
}
@Component({
selector: 'my-list',
template: `
<ul>
<li *ngFor="let l of list" [hidden]="setVisibility(l)">{{l.country}}</li>
</ul>
`,
})
export class List implements OnInit {
list;
ngOnInit(){
this.list = countries
}
setVisibility(country){
console.log('setting');
let hide = false;
if(country.hide === 'true'){
hide = true;
}
return hide;
}
}
我在 setVisibility 方法中放了一个 console.log 来检查这个方法被调用了多少次。我预计它会被调用 6 次(每项 1 次),但实际上它被调用了 24 次(每项 4 次)。为什么这个方法被调用了这么多次? plunker
【问题讨论】:
-
它可以更多,它是关于角度如何读取你的绑定函数,顺便说一句,最好不要在绑定中使用函数,而是在你的原因中,我会说最好像
[hidden]="l.hide === 'true'" -
为了显示它,我已经稍微简化了函数,但实际上该函数应该循环遍历对象属性来设置可见性并且不适合模板
-
我只证明了 plunker 4 次
-
你打开控制台了吗?我在第一次加载时得到日志 12+12 次,每次更换 plunker 时得到 6+6+6+6 次
标签: angular