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).
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With