视图在变量更改后未更新

问题描述 投票:0回答:2

我有一个事件触发了组件中的功能:

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>

我已经对此进行了测试,并且可以工作,但是我需要组件本身来触发更改事件。

谢谢您的帮助。

angular typescript templates view
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>

0
投票

尝试在组件中注入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');
     }

     });
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.