Perhaps this approach may not be the most optimal, but it can work in specific scenarios like this one, where there will always be a single emit handler.
import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core";
@Component({
selector: "app-checkbox",
templateUrl: "./checkbox.component.html",
styleUrls: ["./checkbox.component.css"]
})
export class CheckboxComponent implements OnInit {
@Input() checkboxName;
@Input() checkboxData:any;
@Input() checkBoxLinkedProp:any; // added another property it is the name of the property in the parent component you are updating
@Output() toggle: EventEmitter<any> = new EventEmitter<any>(); // emit a object instead of bool
constructor() {}
ngOnInit() {}
onToggle() {
const checkedOption = this.checkboxData;
this.toggle.emit({checked:checkedOption , checkBoxLinkedProp: this.checkBoxLinkedProp });
}
}
app.component.html
[checkBoxLinkedProp] = "'checkbox1Value'" -- I am passing the property name as a string to the child checkbox component. And when toggled, a single method is called (toggle)="onRoleChangeCheckbox($event)"
this.toggle.emit will emit an object with the specified string prop we passed
<app-checkbox [checkboxName]='checkbox1' [checkboxData]='checkbox1Value'
[checkBoxLinkedProp] = "'checkbox1Value'"
(toggle)="onRoleChangeCheckbox($event)"></app-checkbox>
<app-checkbox [checkboxName]='checkbox2' [checkboxData]='checkbox2Value' (toggle)="onRoleChangeCheckbox($event)"
[checkBoxLinkedProp] = "'checkbox2Value'"
></app-checkbox>
app.component.ts
onRoleChangeCheckbox({checkBoxLinkedProp , checked}) This method will take the property name we passed as a string from the emit event and set the state of the class accordingly.
import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
checkbox1 = 'First checkbox';
checkbox1Value = false;
checkbox2 = 'Second checkbox';
checkbox2Value = false;
onRoleChangeCheckbox({checkBoxLinkedProp , checked}) {
this[checkBoxLinkedProp] = checked; // The property name that was passed to the child is received in this emit event and set accordingly
console.log(this.checkbox1Value , checkBoxLinkedProp); // Tested value for the first checkbox
}
}