这可能不是更好的方法,但它可能在某些情况下有效,在所有情况下都会有一个发射处理程序。
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'" -- 我将道具名称作为字符串传递给子复选框组件。并在切换时调用一个方法 (toggle)="onRoleChangeCheckbox($event)"
this.toggle.emit 将发射带有我们传递的字符串属性的对象
<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}) 这个方法会获取我们从发射事件中作为字符串传递的属性名,并设置类的状态。
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; // property name that passed to child , is received in this emit event and as this will be set
console.log(this.checkbox1Value , checkBoxLinkedProp); // tested value for 1st checkbox
}
}