Search code examples
angularangular-signals

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


Solution

  • 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