0

From the model class, at some random point of time, I need to pass 2 arguments to component to update the html. This argument will be used by the component function to make some UI modifications in the view.

For example:

this.notifyservice.SetTitleMessage(val1: string, val2: string);

Inside the component, i have a different function:

public DisplayTitleMessage(val1: string, val2: string){
this.showitem = (val1 == "item1") ? true: false;
}

These 2 parameters(val1 & val2) should be used to update component member variables(showitem) which in turn update the html.

Can anyone guide me how the component can be updated at any random point of time from within a model class?

Steven
  • 1,996
  • 3
  • 22
  • 33
Arulraj
  • 61
  • 1
  • 2
  • 4

2 Answers2

0

Use a BehaviorSubject in your service and subscribe to it in your component

notify.service.ts

@Injectable()
export class NotifyService {
    public values: BehaviorSubject<any> = new BehaviorSubject(null);

    public SetTitleMessage(val1: string, val2: string) {
        this.values.next({val1: val1, val2: val2});
    }
}

In your component's OnInit

ngOnInit() {
    this.notifyService.values.subscribe((values: any) => {
        if (values)
            this.DisplayTitleMessage(values.val1, values.val2);
    });
}

Now, whenever a change happens, DisplayTitleMessage will be called.

Demo

Hope this helps

cyberpirate92
  • 3,076
  • 4
  • 28
  • 46
0

This is the case what Rxjs is created for. You can subscribe from anywhere to Subject and get fresh data just when the Subject's value is changed. Then, you update a variable in component (template) and Angular's ChangeDetection is triggered.

I created an example: https://stackblitz.com/edit/async-communication-model-template

Do not forget to unsubscribe on component's destruction, otherwise there can appear performance bottlenecks or unexpected behavior.

Angular/RxJs When should I unsubscribe from `Subscription`