本文介绍了在 Angular2 中从 HTML 调用组件方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从 HTML 调用组件方法,还是应该创建另一个组件来处理格式?

<div class="title">{{ item.Title }}</div><p>callComponentMethodHere({{item}})</p>

解决方案
{{callComponentMethodHere(item)}}

但是您应该避免这种情况,因为每次更改检测运行时都会调用该方法.最好在代码中调用该方法(例如在 constructor()ngOnInit() 或事件处理程序中,将结果分配给属性并从视图中改为绑定到该属性.

调用事件处理程序当然没问题:

<button (click)="callComponentMethodHere(item)">点击我</button>

Is it possible to call a component method from HTML, or should I create another component to handle formatting?

<div *ngFor="let item of items">
  <div class="title">{{ item.Title }}</div>
  <p>
    callComponentMethodHere({{item}})
  </p>
</div>
解决方案
{{callComponentMethodHere(item)}}

but you should avoid that because the method will be called every time change detection runs. It's better to call the method in code (for example in the constructor(), ngOnInit(), or an event handler, assign the result to a property and from the view bind to that property instead.

Calling event handlers is fine of course:

<button (click)="callComponentMethodHere(item)">click me</button>

这篇关于在 Angular2 中从 HTML 调用组件方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:15