r/angular • • 1d 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

15 comments sorted by

13

u/Thrawn_86 1d ago

Why not using an input-signal and effect

1

u/HamsterFinancial2616 1d ago edited 1d 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 22h 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 12h ago

ngOnChanges still works!

1

u/Maleficent-Back-6527 19h 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 17h 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.

1

u/Johalternate 17h 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.

1

u/HamsterFinancial2616 17h ago

For example

The userId and postId originate from the parent component. For example, imagine a Post Details page that renders a reusable Post Comments component.

The parent component already has the postId of the currently displayed post and passes it to the child component.

<!-- Parent component -->
<app-post-comments
  [postId]="postId()"
  [userId]="userId()"
/>

The child component accepts these values through input signals:

// Child component
postId = input.required<number>();
userId = input.required<number>();

My goal is to have these input signals trigger the resource() initialized inside a service, so the service can fetch the corresponding comments whenever the postId or userId changes.

The parent already has the values. My question is specifically about bridging the child component's input signals to the service-level resource().

1

u/Johalternate 16h 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 15h 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

3

u/sebastianstehle 23h 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.

2

u/MrFartyBottom 22h 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/SensitiveHearingLoss 15h 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/MarioShroomsTasteBad 8h 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 19h 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.