Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 861
Dživo Jelić Avatar asked Sep 06 '25 21:09

Dživo Jelić


2 Answers

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

like image 191
Chellappan வ Avatar answered Sep 09 '25 17:09

Chellappan வ


The behavior you are looking for seems more like a model() than an input(). A model signal is writeable whereas an input signal is read-only. In this use case:

selected = model<boolean>(false);

// set the model signal's value
this.selected.set(true);

// or update the model signal's value
this.selected.update(() => true);

Please see this Stack Overflow post for more info.

like image 41
CSSBurner Avatar answered Sep 09 '25 18:09

CSSBurner