Angular 5自动更新字符串变量上的另一个变量更改

时间:2018-07-13 18:44:45

标签: string angular angular5 interpolation

是否有一种方法可以在另一个变量更改时更新字符串变量?我有一个使用各种变量构建的字符串。我使用插值在组件的html文件中显示该字符串。但是,如果某个变量更改了字符串用于构建自身的字符串,则该字符串将永远不会更改,因为它们不可更改。唯一的方法是在其他变量之一更改时再次重置字符串。

示例代码:

import { Component} from '@angular/core';

@Component({
    selector: 'app-test-component',
    templateUrl: './test.component.html',
    styleUrls: ['./test.component.scss']
})
export class TestComponent {

    myString = '';
    amount = 0;

    constructor() {
        this.myString = `Hello, you have ${this.amount} dollars.`;

        setTimeout(() => {
            this.amount = 40;
        }, 5000);
    }
}

示例html代码:

<p>{{ myString }}</p>

当然,五秒钟后,该字符串将保持不变,因为我从未对其进行过初始化。有没有一种方法可以自动检测myString内部使用的任何变量是否发生更改,然后更新myString以使用更改后的变量的值?

谢谢,感谢您提供任何信息!

1 个答案:

答案 0 :(得分:3)

您可以使用BehaviorSubject(具有“当前值”概念)进行操作。它存储了发给其使用者的最新值,并且每当有新的Observer进行订阅时,它将立即从BehaviorSubject接收“当前值”。

为数量数据创建单独的服务。

service.ts

//set the initial value here
amount=new BehaviorSubject(0);

component.ts

  

ChangeDetectorRef

     

如果模型中有任何东西(这是什么意思,   您的班级)已更改,但未反映视图,您可能   需要通知Angular以检测那些更改(检测本地更改)   并更新视图。

constructor(private ref: ChangeDetectorRef,subj:SubjectService) {
          subj.amount.subscribe((data)=>{
          this.amount=data;
          this.myString = `Hello, you have ${this.amount} dollars.`;
       //check for changes then it will update the view
          this.ref.markForCheck();  
          })
        setTimeout(() => {
          //change amount data after 1 second 
           subj.amount.next(40);          
        }, 1000);
       }

此处的示例:https://stackblitz.com/edit/changedetection-using-subject?file=src%2Fapp%2Fapp.component.ts

相关问题