ng 中的 Angular 2 隐藏属性用于多次发射



我正在使用一个返回布尔值的函数,以使用 ngFor 循环中的隐藏属性设置项目的可见性。

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 方法中放置了一个控制台.log以检查调用此方法的次数。我预计它会被调用 6 次(每个项目 1 次(,但实际上它被调用了 24 次(每个项目 4 次(。为什么这种方法被调用这么多次? 普伦克

正如RezaRahmati所提到的,它可以被称为更多。现在有四个基本的组件生命周期钩子被调用,这可能就是为什么每个项目收到四个调用的原因。如果要更改数据,将再次调用该函数(每次更改可能调用两次(。由于 ngFor 依赖于数据中的更改,因此它将根据需要重新呈现并调用函数。

此外,如前所述,通过直接访问变量来设置[隐藏]将是一个更快的过程(即使它将被调用的次数与您的函数一样多(。这就是 Angular 管理这些动态变量的方式。这里有一个小的 plunker,向您展示通常如何完成这样的事情:

TypeScript 变量:

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

组件模板:

<ul>
<li *ngFor="let l of list" [hidden]="l.hide">{{l.country}}</li>
</ul>

最新更新