Reputation: 27
I have a problem with updating string variable in Component1 where I change the value in Component2.
Components are independent of each other. Value in HTML template of Component1 doesn't update itself.
Is there a way to force template update? Beside that I tried: subscribe, @Input/@Output - but I might did that in wrong way. Beside that, I think that I can't include selector in template (comp2) because it would display html template from component2 in component1. I hope I'm wrong. Please, lead me out of my mistake.
Upvotes: 0
Views: 1790
Reputation: 6286
You are on the right track. If it's not a parent-child relationship between the components, then no point of looking at @Input
.
If it's just the data that needs to be displayed in the sibling component, then use a service and bind in html. Look at this blog post: https://medium.com/@nodexperts_88267/data-transfer-one-component-to-another-angular-7-c076272c78e1
But if you also need to do something based on the change, then BehaviorSubject
is way to go (Soham's answer).
Upvotes: 0
Reputation: 725
Take a look at Behavior Subject.
// RxJS v6+
import { BehaviorSubject } from 'rxjs';
const subject = new BehaviorSubject(123);
// two new subscribers will get initial value => output: 123, 123
subject.subscribe(console.log);
subject.subscribe(console.log);
// two subscribers will get new value => output: 456, 456
subject.next(456);
// new subscriber will get latest value (456) => output: 456
subject.subscribe(console.log);
// all three subscribers will get new value => output: 789, 789, 789
subject.next(789);
// output: 123, 123, 456, 456, 456, 789, 789, 789
Upvotes: 1