在Angular 8中,如果值在更改后视图不会自动更新,可能是因为没有使用Angular的变更检测机制。
以下是一些解决方法:
import { Component, NgZone } from '@angular/core';
@Component({
selector: 'app-example',
template: `
{{ value }}
`
})
export class ExampleComponent {
value: string;
constructor(private ngZone: NgZone) {}
changeValue() {
this.ngZone.run(() => {
this.value = 'New Value';
});
}
}
import { Component, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-example',
template: `
{{ value }}
`
})
export class ExampleComponent {
value: string;
constructor(private changeDetectorRef: ChangeDetectorRef) {}
changeValue() {
this.value = 'New Value';
this.changeDetectorRef.detectChanges();
}
}
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
{{ value }}
`
})
export class ExampleComponent {
value: string;
changeValue() {
this.value = 'New Value';
}
}
在上述示例中,当点击“Change Value”按钮时,value的值会更改为“New Value”,并且视图会自动更新。