Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Component with ngModel not updating parent model

I am trying to create a wrapper component for inputs such as a checkbox but I cannot get the parent (inputValue) variable to change, even though it is set as an ngModel.

This is my component definition:

@Component({
selector: 'my-checkbox',
inputs: ['inputValue', 'label'],    
template: `
    <div class="ui checkbox">
      <input type="checkbox" name="example" [(ngModel)]="inputValue" (change)="onChange($event)">
      <label>{{label}}</label>
    </div>`
})

export class CheckboxComponent {    

inputValue: boolean;

onChange(event) {
    this.inputValue = event.currentTarget.checked;
    console.log(this.inputValue);
}}

And I am using it like this in the parent view:

<my-checkbox [inputValue]="valueToUpdate" [label]="'Test Label'"></my-checkbox>

The console does log correctly and I can see that the internal (inputValue) is updating but not the external 'valueToUpdate' (the ngModel two-way binding is not updating correctly).

like image 376
EnlitenedZA Avatar asked Jan 28 '26 05:01

EnlitenedZA


1 Answers

You need to define an output for your component and use the EventEmitter class to fire the corresponding event.

@Component({
  selector: 'my-checkbox',
  inputs: ['inputValue', 'label'],    
  outputs: ['inputValueChange']
  template: `
    <div class="ui checkbox">
      <input type="checkbox" name="example" [(ngModel)]="inputValue" (change)="onChange($event)">
      <label>{{label}}</label>
    </div>`
})
export class CheckboxComponent {    

  inputValue: boolean;
  inputValueChange: EventEmitter<any> = new EventEmitter();

  onChange(event) {
    this.inputValue = event.currentTarget.checked;
    console.log(this.inputValue);
    this.inputValueChange.emit(this.inputValue);
  }
}

This way you will be able to use two binding for your sub component:

<my-checkbox [(inputValue)]="valueToUpdate" [label]="'Test Label'">
</my-checkbox>
like image 196
Thierry Templier Avatar answered Jan 31 '26 02:01

Thierry Templier