在模板中使用函数时如何停止 angular 中函数的多重触发?
How to stop multi trigger of functions in angular when using functions in template?
我在HTML模板中使用函数,我不能直接使用变量,因为条件有点复杂。
我的问题是模板中的函数被调用了多次。
例如 this Stackblitz (最小、可重现的示例)
加载时记录 get Name was called
4 次,单击“更改版本”按钮后记录 2 次。
我想在加载时调用一次,每次点击只调用一次。为了性能我怎样才能做到这一点
设置组件的changeDetection
模式为OnPush
https://angular.io/api/core/ChangeDetectionStrategy
使用 OnPush
将告诉 Angular 仅在组件的 @Input()
绑定发生更改时才呈现模板。默认模式将在每个摘要周期对模板执行更改检测,并且由于表达式使用的是函数,因此每次都必须调用它以查看值是否已更改。
@Component({
selector: 'hello',
template: `<h1>Hello {{getName()}}!</h1>
<button (click)="changeName()"> this</button>`,
styles: [`h1 { font-family: Lato; }`],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class HelloComponent implements OnInit{
// ....
}
这是一篇关于该主题的博客:
https://netbasal.com/a-comprehensive-guide-to-angular-onpush-change-detection-strategy-5bac493074a4
我在HTML模板中使用函数,我不能直接使用变量,因为条件有点复杂。
我的问题是模板中的函数被调用了多次。
例如 this Stackblitz (最小、可重现的示例)
加载时记录 get Name was called
4 次,单击“更改版本”按钮后记录 2 次。
我想在加载时调用一次,每次点击只调用一次。为了性能我怎样才能做到这一点
设置组件的changeDetection
模式为OnPush
https://angular.io/api/core/ChangeDetectionStrategy
使用 OnPush
将告诉 Angular 仅在组件的 @Input()
绑定发生更改时才呈现模板。默认模式将在每个摘要周期对模板执行更改检测,并且由于表达式使用的是函数,因此每次都必须调用它以查看值是否已更改。
@Component({
selector: 'hello',
template: `<h1>Hello {{getName()}}!</h1>
<button (click)="changeName()"> this</button>`,
styles: [`h1 { font-family: Lato; }`],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class HelloComponent implements OnInit{
// ....
}
这是一篇关于该主题的博客:
https://netbasal.com/a-comprehensive-guide-to-angular-onpush-change-detection-strategy-5bac493074a4