问题描述: 在Angular中,当变量在ngAfterViewInit生命周期钩子中被初始化后,它们可能会在之后被重置,导致无法正确使用。
解决方法:
import { Component, AfterViewInit, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-my-component',
template: `{{ myVariable }}`,
})
export class MyComponent implements AfterViewInit {
myVariable: string;
constructor(private cdr: ChangeDetectorRef) {}
ngAfterViewInit() {
this.myVariable = 'initial value';
this.cdr.detectChanges();
}
}
import { Component, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-my-component',
template: `{{ myVariable }}`,
})
export class MyComponent implements AfterViewInit {
myVariable: string;
ngAfterViewInit() {
setTimeout(() => {
this.myVariable = 'initial value';
});
}
}
这两种方法都可以确保在ngAfterViewInit生命周期钩子中初始化的变量不会被重置。选择哪种方法取决于具体情况和个人偏好。
上一篇:Angular - 变量未定义