r/angular • • 8d ago

Using an @Input() Setter to Bridge Component Inputs with Service-Level Signals

I have a question regarding Angular's @Input setter and Signals.

I'm building a reusable service that uses Angular's resource() API to handle data fetching. Since resource() depends on signals for reactive updates, I need a way to pass the component's input value to the service layer.

My current approach is to use an @Input setter to update a signal inside the service.

Example:

// Service
readonly userId = signal<number | null>(null);

protected readonly userResource = resource({
  params: () => {
    const userId = this.userId();
    return userId ? { userId } : undefined;
  },
  loader: ({ params }) => this.fetchData(params)
});

// Component
@Input() public set userId(value: number) {
  this.reusableService.userId.set(value);
}

I'm feeling a bit stuck deciding whether this is the right approach.
Is this a proper approach, or would you consider using an @Input() setter as a bridge between the component input and a service-level signal a workaround or an anti-pattern?

3 Upvotes

16 comments sorted by

14

u/Thrawn_86 8d ago

Why not using an input-signal and effect

1

u/HamsterFinancial2616 8d ago edited 8d ago

I also tried this approach:

effect(() => {
  this.reusableService.userId.set(this.userId());
});

However, I'm unsure whether this is the correct approach because I've read that writing to signals inside an effect() is generally not recommended.

Another reason I'm hesitant is that this is essentially using one signal to synchronize another signal.

5

u/Thrawn_86 8d ago

Yes you have to be careful with writing to signals in effects, if you have komplex logic it can be difficult when you trigger a chain of other effects with that signal-change. In previous angular-versions you had to explicit enable writing to signals in effects.

But in this case its simple so i dont see a risk here.

Why i am suggesting not using @input? I got the impression that angular is reducing the use of @-decorators by giving signal-alternatives f.e. input, viewchild, contenchild, etc. I see a possible technical dept here if they decide to kill @input. The other thing is, you shouldn't mix @input and input signals in a component, there are timing differences - so if your component has other input-signals you can get some strange sideffects.

1

u/valendinosaurus 7d ago

ngOnChanges still works!

2

u/Johalternate 8d ago

If userId is an input to a component, it means that the parent component gets userId first, how does the parent component get userId?

You can do this in many different ways depending on where userId originates, if you could share that detail we could provide a better approach.

0

u/[deleted] 8d ago

[deleted] — view deleted comment

1

u/Johalternate 8d ago

I understand that, the question is, how did the parent component get userId in the first place?

If for example it came from a route param, those are readable synchronously via ActivatedRoute, or subscribe to param changes using Route and call reusableService.userId.set inside the subscription.

You can use ngxtension's connect. https://ngxtension.dev/utilities/signal-async/connect/, or just copy their implementation which is fairly simple.

1

u/HamsterFinancial2616 8d ago

Thanks! I'll check that one. I also went ahead and implemented my own approach to this. Here's the StackBlitz demo if you want to check it out:

https://stackblitz.com/edit/stackblitz-starters-gtpdjxuk?file=src%2Fapp.ts

1

u/Johalternate 3d ago

Hey, I finally got the time to review your code example and I have some feedback, on how it can be improved. These are all opinions and I dont think there is a definitive approach.

Something that caught my attention is that App component owns the user and post ids, which you pass to Todo and Post, and then they have to propagate their input to the service.

Im not a big fan of components owning data, even in the case of components that are never destroyed such as App. I would rather have an injectable or service own the data and allow components to read and update it.

I also dont like that you are reading the signal in a getter method instead of the template, one of the value propositions of signals is their reactivity, you are bypassing that by reading them synchronously in a getter and then using the getter in a template. The only reason it works in this case is because some user actions trigger change detection (like button clicks or input fields interactions), so the user click forces change detection.

What I would do is, make services own the IDs, inject the services in the Post and Todo components so they can read their respective resources, and also inject them in the app component so it can send updates.

Check my approach: https://stackblitz.com/edit/stackblitz-starters-ayihkpmw?file=src%2Fcomment%2Fcomment.ts

Added an extra example showing that when a resource params return undefined the loader wont trigger, which is useful for controlling when something is first fetched. Notice how the other examples will call the API as soon as they are instantiated.

4

u/sebastianstehle 8d ago

Technically you can do it, but this makes the service useless and you expose internal implementation details.

At least I would make a method like `loadUser(id: string)` in the service. You just moved code arround at the moment.

4

u/SensitiveHearingLoss 8d ago

Assuming that your parent component passes a value into the child component like this:

@for (post of posts(); track post.id) {
<app-post-comments [postId]="post.id" />
}

Your component receives the input as such:

export class PostCommentsComponent {
private readonly commentsService = inject(PostCommentsService);

readonly postId = input.required<number>();

readonly comments = this.commentsService.getComments(this.postId);
}

Then your service can simply contain a method which expects a signal:

@Injectable({ providedIn: 'root' })
export class PostCommentsService {
getComments(postId: Signal<number>) {
return httpResource<Comment[]>(
() => `/api/posts/${postId()}/comments`
);
}
}

You don’t need effects or anything. When the input value changes, the service method will be triggered.

(I hope)

1

u/Maleficent-Back-6527 8d ago

Why do you even need to do that in the component. Since your child component is simply setting the new value from the parent into the service, it seems to me like you don’t even need a child component for that. You could directly update your service signal from the parent component!

1

u/HamsterFinancial2616 8d ago

I'm trying to cover a use case where a value is passed as an input to a child component, and I want that input to trigger updates to the resource() initialized in the service.

For example, I have a reusable Post Comments component that accepts a postId as an input. Whenever the postId changes, I want the resource in the service to automatically fetch the comments associated with that post.

That's why I'm exploring ways to bridge the component input with the service-level signal.

2

u/MrFartyBottom 8d ago

I used to use input setters but feel like using any RxJs based inputs once you have migrated to signals is a bit wiffy. That is why effects exist.

1

u/MarioShroomsTasteBad 7d ago

Yeah I feel like an effect off of a signal input works here. If the id is in the route you could also use the new router resource api, or traditional data resolver.

1

u/Dull-Structure-8634 8d ago

I think you're trying to shoehorn signals where they don't necessarily need to be there. You already have what you need: RxJs.

Use transform your input signal into an observable with toObservable, subscribe to it in the constructor and voilà, it's working, simple and easy to understand.