如何在模板绑定中从 Angular 4 访问 getter/setter 访问器?

2023-11-23

假设我有以下 getter/setter 方法

get next() {
  console.log(this.people[this._index], this._index);
  return this.people[this._index];
}

set next(i: any) {
  this._index = (+i) + 1;
  this._index = (+i) % this.people.length;
}

我想用以下方式称呼它:

<ng-template ngFor let-person="$implicit" [ngForOf]="people" let-i=index let-last=last>
  <app-card [cardItem]="people[i]" [nextCard]="next(i)"></app-card>
</ng-template>

PS:将其视为圆形阵列。我需要上一个、当前和下一个项目。

但是我收到以下错误

Angular:成员“下一个”不可调用

这是为什么?解决办法是什么?

Thanks

Edit

谢谢你们的帮助和解释。在你的帮助下,我设法让它发挥作用:

<app-card [currentCard]="people[i]" [nextCard]="people[i === people.length - 1 ? 0: i + 1]" [prevCard]="i == 0 ? people[people.length - 1] : people[i - 1]"></app-card>

所以它几乎是圆形阵列。 假设我们有以下内容:

people["James Dan", "Aluan Haddad", "Jota Toledo"]

就这么几个条件:

  1. 如果我站在数组的开头(即index = 0) - 然后我的prevpeople[people.length - 1]这是数组中的最后一个元素。如果我的当前位于索引 1,那么我的上一个将是索引 0,下一个将是索引 2。

一般来说,Angular 模板语法是 JavaScript 语法的子集,但存在一些显着差异和许多限制。

然而,这里的内容实际上在 JavaScript 中也是无效的。调用属性访问器是无效的。曾经。

给定以下属性

get p() {
  console.info('read p');
  return this.wrapped;
}
set p(value) {
  console.info('wrote p');
  this.wrapped = value;
}

The get当读取如此命名的属性时,将隐式调用访问器。

例如:

console.log(o.p); // read p

The set当写入如此命名的属性时,将隐式调用访问器。

例如:

o.p = x; // wrote p;

相同的规则也适用于 Angular 模板。

然而,你的例子

<app-card [cardItem]="people[i]" [nextCard]="next(i)">

表明该属性不是您想要的。

属性的正确用法意味着以下语法

<app-card [cardItem]="people[i]" [nextCard]="next = i">

我不相信 Angular 模板语法支持它,即使它是没有多大意义并且难以阅读。

相反,您应该创建一个返回值的方法

getNext(i: number) {
  this._index = i + 1;
  this._index = i % this.people.length;
  return this.people[this._index];
}

然后在您的模板中用作

<app-card [cardItem]="people[i]" [nextCard]="getNext(i)">

话虽如此,我认为整个设计都是有问题的。您似乎正在经历一些扭曲,以独立于自然维护它的数组来存储多余的可变状态。

我相信通过完全删除该方法和属性并使用,您会得到更好的服务

<app-card
  *ngFor="let person of people; let i = index"
  [previousCard]="people[i === 0 ? people.length - 1 : i - 1]" 
  [cardItem]="person"
  [nextCard]="people[i === people.length - 1 ? 0 : i + 1]">

如果您想要更清晰的语法,您可以定义一个属性,其中包含get仅访问器,它返回数组的视图作为对象previous, current, and next特性。

get peopleAsPreviousCurrentAndNextTriplets() {
  return this.people.map((person, i) => ({
    previous: this.people[i === 0 ? this.people.length - 1 : i - 1],
    current: person,
    next: this.people[i === this.people.length - 1 ? 0 : i + 1]
  }));
}

这在复杂的代码中更具可读性,因为它抽象了我们可以直接使用的更多语义属性的索引。也许更重要的是,它使 TypeScript 的世界一流工具能够验证计算。

<app-card
  *ngFor="let item of peopleAsPreviousCurrentAndNextTriplets"
  [previousCard]="item.previous" 
  [cardItem]="item.current"
  [nextCard]="item.next">

这样我们就回到原点了。注意我们如何定义get访问器以及我们如何读取它定义的属性(),隐式调用该访问器。

最后一个例子对于这种情况可能有点过分了,但我认为它仍然有用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在模板绑定中从 Angular 4 访问 getter/setter 访问器? 的相关文章

随机推荐