首页  >  文章  >  web前端  >  Angular中为什么不要在模板中调用方法

Angular中为什么不要在模板中调用方法

青灯夜游
青灯夜游转载
2021-09-30 10:36:471856浏览

本篇文章给大家介绍一下Angular中不在模板(template)里面调用方法的原因,以及解决方法,希望对大家有所帮助!

Angular中为什么不要在模板中调用方法

在运行 ng generate component f3fc15c0228dc320ab4107d8220f2b42 命令后创建angular组件的时候,默认情况下会生成四个文件:

  • 一个组件文件 f3fc15c0228dc320ab4107d8220f2b42.component.ts
  • 一个模板文件 f3fc15c0228dc320ab4107d8220f2b42.component.html
  • 一个 CSS 文件, f3fc15c0228dc320ab4107d8220f2b42.component.css
  • 测试文件 f3fc15c0228dc320ab4107d8220f2b42.component.spec.ts

【相关教程推荐:《angular教程》】

模板,就是你的HTML代码,需要避免在里面调用非事件类的方法。举个例子

<!--html 模板-->
<p>
  translate Name: {{ originName }}
</p>
<p>
  translate Name: {{ getTranslatedName(&#39;你好&#39;) }}
</p>
<button (click)="onClick()">Click Me!</button>
// 组件文件
import { Component } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;my-app&#39;,
  templateUrl: &#39;./app.component.html&#39;,
  styleUrls: [&#39;./app.component.css&#39;],
})
export class AppComponent {
  originName = &#39;你好&#39;;

  getTranslatedName(name: string): string {
    console.log(&#39;getTranslatedName called for&#39;, name);
    return &#39;hello world!&#39;;
  }

  onClick() {
    console.log(&#39;Button clicked!&#39;);
  }
}

1.png

我们在模板里面直接调用了getTranslatedName方法,很方便的显示了该方法的返回值 hello world。 看起来没什么问题,但如果我们去检查console会发现这个方法不止调用了一次。

2.png

并且在我们点击按钮的时候,即便没想更改originName,还会继续调用这个方法。

3.png

原因与angular的变化检测机制有关。正常来说我们希望,当一个值发生改变的时候才去重新渲染对应的模块,但angular并没有办法去检测一个函数的返回值是否发生变化,所以只能在每一次检测变化的时候去执行一次这个函数,这也是为什么点击按钮时,即便没有对originName进行更改却还是执行了getTranslatedName

当我们绑定的不是点击事件,而是其他更容易触发的事件,例如 mouseenter, mouseleave, mousemove等该函数可能会被无意义的调用成百上千次,这可能会带来不小的资源浪费而导致性能问题。

一个小Demo:

https://stackblitz.com/edit/angular-ivy-4bahvo?file=src/app/app.component.html

大多数情况下,我们总能找到替代方案,例如在onInit赋值

import { Component, OnInit } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;my-app&#39;,
  templateUrl: &#39;./app.component.html&#39;,
  styleUrls: [&#39;./app.component.css&#39;],
})
export class AppComponent implements OnInit {
  originName = &#39;你好&#39;;
  TranslatedName: string;

  ngOnInit(): void {
    this.TranslatedName = this.getTranslatedName(this.originName)
  }
  getTranslatedName(name: string): string {
    console.count(&#39;getTranslatedName&#39;);
    return &#39;hello world!&#39;;
  }

  onClick() {
    console.log(&#39;Button clicked!&#39;);
  }
}

或者使用pipe,避免文章过长,就不详述了。

更多编程相关知识,请访问:编程视频!!

以上是Angular中为什么不要在模板中调用方法的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:juejin.cn。如有侵权,请联系admin@php.cn删除