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

lxf2023-03-12 19:53:01

本文给大家介绍一下Angular中没有在模版(template)里边调用方法的主要原因,及其解决方案,希望能帮助到大家!

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

在运行 ng generate component <component-name> 指令后创建angular元件的情况下,默认设置状况下能形成四个文档

  • 一个部件文档 <component-name>.component.ts
  • 一个模板文件 <component-name>.component.html
  • 一个 CSS 文档, <component-name>.component.css
  • 测试文件 <component-name>.component.spec.ts

【有关实例教程强烈推荐:《angular教程》】

模版,就是你HTML编码,必须防止在房间里启用非事情类的方法。举例说明

<!--html 模版-->
<p>
  translate Name: {{ originName }}
</p>
<p>
  translate Name: {{ getTranslatedName('您好') }}
</p>
<button (click)="onClick()">Click Me!</button>
// 部件文档
import { Component } from '@angular/core';

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

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

  onClick() {
    console.log('Button clicked!');
  }
}

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

大家在模版里边立即启用了getTranslatedName方式,非常方便显示此方法的传参 hello world。 看上去没有问题,但如果我们来检查console就会发现用这种方法不仅启用了一次。

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

而且在咱们点击图标时,就算没有想变更originName,还会调用这种方法。

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

缘故与angular的变化检测体制相关。一般来说我希望,当一个值发生变化的时候才会去再次3D渲染相对应的控制模块,但angular并没方法去检验一个函数的返回值是不是产生变化,所以只好在每一次检验转变时去实行一次这一函数公式,这也就是为什么点击图标时,即使没有对originName开展变更却仍然实施了getTranslatedName

在我们关联的并不是js点击事件,反而是别的比较容易触发的事情,比如 mouseenter, mouseleave, mousemove等该函数公式有可能被毫无意义的启用不计其数次,这可能会带来很大的资源浪费现象而造成兼容性问题。

一个小Demo:

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

绝大多数情况下,大家都能找到替代选择,比如在onInit取值

import { Component, OnInit } from '@angular/core';

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

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

  onClick() {
    console.log('Button clicked!');
  }
}

或使用pipe,防止文章内容太长,也不详细描述了。

大量程序编写基本知识,请访问:编程视频!!

以上就是关于Angular中为什么不要在模版中调用方法的具体内容,大量欢迎关注AdminJS其他类似文章!