然而,这里的内容在JavaScript中实际上也是无效的。调用属性访问器无效。曾经
给定以下属性
get p() {
console.info('read p');
return this.wrapped;
}
set p(value) {
console.info('wrote p');
this.wrapped = value;
}
这个
get
当读取如此命名的属性时,会隐式调用访问器。
例如:
console.log(o.p); // read p
set
当写入如此命名的属性时,会隐式调用访问器。
例如:
o.p = x; // wrote p;
同样的规则适用于角度模板。
然而,您的示例
<app-card [cardItem]="people[i]" [nextCard]="next(i)">
<app-card [cardItem]="people[i]" [nextCard]="next = i">
我认为角度模板语法不支持这一点,即使它没有多大意义,也很难阅读。
相反,您应该创建一个返回值的方法
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]">
如果需要更简洁的语法,可以使用
收到
previous
,
current
和
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]
}));
}
<app-card
*ngFor="let item of peopleAsPreviousCurrentAndNextTriplets"
[previousCard]="item.previous"
[cardItem]="item.current"
[nextCard]="item.next">
收到
访问器以及如何读取它定义的属性
()
最后一个例子对于这个场景来说可能有些过头了,但我认为它还是有用的。