【问题标题】:Angular 2 hidden attribute inside ngFor firing multiple timesngFor中的Angular 2隐藏属性多次触发
【发布时间】: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


【解决方案1】:

正如 RezaRahmati 提到的,它可以被称为更多。现在有四个基本组件lifecycle hooks 被调用,这可能就是每个项目收到四个调用的原因。如果您要更改数据,将再次调用该函数(每次更改可能两次)。由于 ngFor 依赖于数据的变化,它会根据需要重新渲染并调用函数。

此外,如前所述,通过直接访问变量来设置 [hidden] 将是一个更快的过程(即使它被调用的次数与您的函数一样多次)。这就是 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>

【讨论】:

    猜你喜欢
    • 2017-04-13
    • 2016-07-28
    • 1970-01-01
    • 2017-12-30
    • 2017-03-07
    • 2018-12-25
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多