Is there a way to update a string variable when another variable changes? I have a string that is built by using various variables. I display that string in the component\'s htm
You can do that using BehaviorSubject, which has a notion of "the current value". It stores the latest value emitted to its consumers, and whenever a new Observer subscribes, it will immediately receive the "current value" from the BehaviorSubject.
Create separate service for amount data.
service.ts
//set the initial value here
amount=new BehaviorSubject(0);
component.ts
ChangeDetectorRef
What it means if there is a case where any thing inside your model ( your class ) has changed but it hasn't reflected the view, you might need to notify Angular to detect those changes ( detect local changes) and update the view.
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);
}
example here: https://stackblitz.com/edit/changedetection-using-subject?file=src%2Fapp%2Fapp.component.ts