从Angular2中的HTML调用组件方法 [英] Call a component method from HTML in Angular2

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

问题描述

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

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)}}

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

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调用组件方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆