代码之家  ›  专栏  ›  技术社区  ›  James

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

  •  5
  • James  · 技术社区  · 7 年前

    假设我有以下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:将其视为圆形阵列。我需要上一个、当前和下一个项目。

    然而,我得到了以下错误

    角度:不可调用中的成员“next”

    谢谢你们的帮助和解释。在你的帮助下,我成功地做到了:

    <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 prev people[people.length - 1] 哪个是数组中的最后一个元素。如果我的电流在索引1上,那么我的上一个将是索引0,下一个将是索引2。
    1 回复  |  直到 7 年前
        1
  •  19
  •   Aluan Haddad Vikrant Kashyap    6 年前

    然而,这里的内容在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">
    

    收到 访问器以及如何读取它定义的属性 ()

    最后一个例子对于这个场景来说可能有些过头了,但我认为它还是有用的。