o.o
o.o

Reputation: 3751

Angular 5 auto update string variable on another variable change

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 html file using interpolation. However, if a variable changes that the string was using to build itself, the string will never change because they not mutable. Only way would be to reset the string again when one of the other variables change.

Sample ts code:

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);
    }
}

Sample html code:

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

Of course, after five seconds, the string stays the same because I never reinitialized it. Is there a way to automatically detect if any of the variables being used inside myString change, then update myString to use the values of the changed variables?

Thank you, any information is appreciated!

Upvotes: 1

Views: 4131

Answers (1)

Chellappan வ
Chellappan வ

Reputation: 27409

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

Upvotes: 4

Related Questions