【问题标题】:Angular: how can I make a class member private but accesible for the template?Angular:如何使类成员私有但可用于模板?
【发布时间】:2020-06-12 03:39:23
【问题描述】:

我有 followign 组件

组件 ts:

export class calculator {
    public elements;
    public findAll() {
     // backend stuff for retrieving data and assigning it to elements
    }

    public delete(obj) {
     // backend stuff for deleting obj
    }

    public save(obj) {
     // backend stuff for saving obj
    }
}

组件模板:

<div>
  <button (click)="findAll()">Start!</button>
  <div>
     <div *ngFor="let elem for elements">
       <span>{{elem.name}}</span>
       <button (click)="delete(elem)"></button>
     </div>
  </div>
</div>

我希望只有 save 方法可以从类外访问,有没有办法实现这一点?

class anotherClass {
   this.calculator.save(formula); // can't access to findAll or delete
}

编辑: 我已尝试使用受保护的访问器,但出现错误:

'findAll' 是受保护的,只能在类 'calculator' 中访问 及其子类。

【问题讨论】:

  • 使用不能在模板中使用的受保护私有变量。它将在 aot 构建中失败
  • 这就是受保护的作用,如果您需要从类/子类外部访问 findAll 则将其公开
  • 对,我收到此错误是因为模板中使用了 findAll。我希望该方法可用于模板,但对于其余类是私有的。看起来受保护的访问器也将其设为模板私有。
  • 好吧,你不能这样做

标签: javascript angular


【解决方案1】:

不,你不能这样做。模板不存在于组件类中,而是存在于它们之外。因此模板无法访问私有成员

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 2011-02-17
    相关资源
    最近更新 更多