Currently, I am in the process of learning Angular 2 and find myself unsure about the most efficient way to update the view.
For instance, let's say I have two components: User and Main.
The User component retrieves a list of users from the UserService. Upon initialization, this component reads all users from the service and assigns them to a member within the component.
When a different user is selected, the component simply passes on the value (id) to the UserService, which then stores the user object in a member called "selected". The UserService includes a method called getSelected() that returns the currently selected user.
Everything seems to be functioning correctly so far (on a side note, how can private/public members/methods be implemented in TypeScript?)
My current goal is to display the selected User in the main component. How can I achieve this update where every change in selection is relayed through the service and captured by the main component?
Here is an example code snippet found in the user controller for selecting a user:
onChange(event) {
this._userService.select(event.source.value);
}
Within the user service, the selection is stored like this:
select(userId: number) {
for (const user of this.users) {
if (user.getId() === userId) {
this.selected = user;
}
}
}
Meanwhile, in the main component:
getUser() {
return this._userService.getCurrent();
}
I attempted the following in HTML:
<div fxLayout="column" fxFlex fxLayoutAlign="center center">
<div>Selected User: {{getUser()}}</div>
</div>
Unfortunately, it does not seem to work as intended. What would be the best approach with Angular 2/TypeScript? Should I directly access the service in my HTML or is there a better alternative you could suggest?
Regards, n00n