Angular 5 auto update string variable on another variable change

前端 未结 1 1833
南笙
南笙 2021-01-25 03:25

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

相关标签:
1条回答
  • 2021-01-25 04:07

    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

    0 讨论(0)
提交回复
热议问题