当按钮点击时,组件的ngOnInit或构造函数会执行多次的原因可能是因为每次点击按钮都会重新创建组件实例。解决方法可以通过以下两种方式来解决:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
`,
})
export class ExampleComponent {
showComponent = false;
toggleComponent() {
this.showComponent = !this.showComponent;
}
}
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-example',
template: `
`,
})
export class ExampleComponent implements OnInit {
isInitialized = false;
ngOnInit() {
if (this.isInitialized) {
return;
}
// 组件的初始化逻辑
this.isInitialized = true;
}
initializeComponent() {
this.ngOnInit();
}
}
以上是两种解决方法,你可以根据具体情况选择适合你的方式来解决组件的ngOnInit或构造函数多次执行的问题。