一般来说,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
访问器以及我们如何读取它定义的属性()
,隐式调用该访问器。
最后一个例子对于这种情况可能有点过分了,但我认为它仍然有用。