Angular change input signal value from within component
Asked Answered
P

2

8

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 :)

Potted answered 2/2 at 17:2 Comment(2)
try this.selected.set(true)Protein
@NarenMurali Doesnt work either type is InputSignal<boolean, boolean>Aureolin
C
11

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

Caruso answered 2/2 at 17:29 Comment(5)
this gives an example of how to solve my problem although first answer is better in terms of information.Aureolin
@DživoJelić Updated with few more information. please checkIndentation
thx that is what i am really looking forward to in the next releases :)Aureolin
@DživoJelić model input feature available in angular latest releaseIndentation
Angular model documentation here: linkCotoneaster
P
6

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 only meant as a alternative for @Input of angular, but its special because 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!

Protein answered 2/2 at 17:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.