Simple Angular Service using signals

Simple Angular Service using signals

Related to Angular 17th launching I try to learn how works signals. So check how to share data between 2 components.

This example use standAlone components but the workflow is very similar compared with previous versions.

Create a service with data attribute (assigning the signal) with a number value. and set 2 methods to manage signal value.

store.ts

Consuming signal between components...

Now in main (standAlone component) using a constructor make an instance from Store to local store attribute. Then create a get returning the signal value executed.

main.ts

In signals the expression require an execution to listen global state. It can be from service or component, for this example from service

I prefer avoid to write html code in main.ts component to keep all separated and more readable but if you prefer just replace

templateUrl: './main.html'

with

template: '<h2>This is main with Data {{dataValue}}</h2>'.

Second Component

Create a header component on this path components/header as a traditional angular component.

header.ts

to get dataValue is the same approach but to change data create changeData method to pass the new value.

header.html

Using (click) directive set new value adding a number to the current dataValue. That trigger a new value listened globally for all components.

Conclusion

That new way to share data is more simple to write and read, signals definitely does not replace the previous way since RxJS has a huge range of operators and features but is a huge beginning...

Github code

DEV.to article

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics