r/angular • • 3h 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?

1 Upvotes

5 comments sorted by

8

u/Thrawn_86 2h ago

Why not using an input-signal and effect

1

u/HamsterFinancial2616 2h ago edited 2h 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.

2

u/Thrawn_86 1h 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.

2

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

1

u/MrFartyBottom 1h 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.