Dživo Jelić
Dživo Jelić

Reputation: 2143

Angular change input signal value from within component

I am new to signals in angular and i want to change my input signal from within component

selected = input(false);

I would except to do somethin like this

this.selected().set(true)
this.selected.set(true)

But that doesn't seem to work. What am i missing :)

Upvotes: 17

Views: 33969

Answers (2)

Naren Murali
Naren Murali

Reputation: 57791

In the docs these is the details for input signal!

InputSignal

InputSignal is represents a special Signal for a directive/component input.


An input signal is similar to a non-writable signal except that it also carries additional type-information for transforms, and that Angular internally updates the signal whenever a new value is bound.

So this type of signal is a good alternative for @Input of angular, it also has the power to throw an error when no input is provided, when you configure it as selected = input.required so it can be used to mandate passing input properties!

Since the signal is non-writable we cannot set the value, we can only accept values coming from the parent element!

Upvotes: 6

Chellappan வ
Chellappan வ

Reputation: 27439

As of Angular 17.2.0-next.1:

Input signals are read-only inside the component that receives them.you can't change the input signal directly. you have to use a computed property to calculate a new value based on it.

_select = signal(false);
hasSelected = computed(() => this.selected() || this._select());

Input Signal RFC

Update:

In Angular 17.2.0-rc.1 release, we can use the model input feature. This feature enables model() to return a writable signal that implicitly defines an input/output pair. This pair can be used either in two-way bindings to keep two values in sync or by binding individually to the input and output.

@Directive({
  selector: 'counter',
  standalone: true,
  host: {
    '(click)': 'increment()',
  }
})
export class Counter {
  value = model(0);

  increment(): void {
    this.value.update(current => current + 1);
  }
}

@Component({
  template: `<counter [(value)]="count"/> The current count is: {{count()}}`,
})
class App {
  count = signal(0);
}

Initial implementation PR

Upvotes: 25

Related Questions