我有一个事件触发了组件中的功能:
componentA.ts
html = 'hey';
this.onElementSelected(r => this.change());
public change() {
console.log(this.html);
if (this.html === 'hey') {
this.html = 'oh, hello!';
console.log(this.html);
} else {
this.html = 'hey';
}
}
componentA.html
这是相关模板的代码:
<div *ngIf="html">{{html}}</div>
我可以用console.log()看到html变量的变化,但是在模板中却没有变化。 如何更新模板?请不要建议在模板中使用按钮:
<button (click)="change()">Change</button>
我已经对此进行了测试,并且可以工作,但是我需要组件本身触发更改事件。
谢谢您的帮助。
答案 0 :(得分:1)
尝试在组件中注入 ngZone 并像这样执行其运行功能中的更改
import {NgZone} from '@angular/core';
class YourClass {
constructor(private ngZone: NgZone) {
this.htmlSource = new BehaviorSubject('hey');
this.html$ = this.htmlSource.asObservable();
}
this.onElementSelected(r => this.change());
public change() {
console.log(this.htmlSource.value);
this.ngZone.run(() => {
if (this.htmlSource.value === 'hey') {
this.htmlSource.next('oh, hello!');
console.log(this.htmlSource.value);
} else {
this.htmlSource.next('hey');
}
});
}
}
答案 1 :(得分:1)
您是否使用过ChangedetectionStrategy.OnPush?此选项使Angular与自动更新视图分离。因此,您必须告诉Angular应该何时更新视图。
如果这样,告诉您组件的视图进行更新:
import { ChangeDetectorRef } from '@angular/core';
...
constructor(private cd: ChangeDetectorRef) {}
if (this.html === 'hey') {
this.html = 'oh, hello!';
this.cd.detectChanges();
...
答案 2 :(得分:0)
尝试使用带有BehaviorSubject的Observable,如下所示:
public html$: Observable<string>;
private htmlSource: BehaviorSubject<string>();
constructor() {
this.htmlSource = new BehaviorSubject('hey');
this.html$ = this.htmlSource.asObservable();
}
this.onElementSelected(r => this.change());
public change() {
console.log(this.htmlSource.value);
if (this.htmlSource.value === 'hey') {
this.htmlSource.next('oh, hello!');
console.log(this.htmlSource.value);
} else {
this.htmlSource.next('hey');
}
}
然后在component.html中:
<div *ngIf="html$ | async as html">{{html}}</div>