我正在将自定义组件与ControlValueAccessor
一起用于multiCheckbox。
checkbox.component.ts
:
import {
Component,
OnInit,
forwardRef,
Input,
ViewChild,
ElementRef,
Output,
EventEmitter
} from "@angular/core";
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from "@angular/forms";
@Component({
selector: "app-checkbox",
templateUrl: "./checkbox.component.html",
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CheckboxComponent),
multi: true
}
]
})
export class CheckboxComponent implements OnInit, ControlValueAccessor {
isChecked = false;
public userStatus = [
{name: 'user1', checked: true},
{name: 'user2', checked: false},
{name: 'user3', checked: false}
]
propagateChange = (_: any) => {};
onTouchedCallback = () => {};
constructor() {}
ngOnInit() {}
writeValue(value: any) {
this.checked = value;
}
submit($event: Event) {
console.log(this.userStatus);
}
registerOnChange(func: any) {
this.propagateChange = func;
}
registerOnTouched(func: any) {
this.onTouchedCallback = func;
}
}
checkbox.component.html
:
<section class="checkbox-section" *ngFor="let opt of userStatus">
<mat-checkbox [(ngModel)]="opt.checked" name="{{opt.name}}">{{ opt.name }}</mat-checkbox>
<br>
CheckBox Name {{ opt.name }}
</section>
<br><br>
{{userStatus | json}}
到此为止,它工作正常。但是问题是我无法将ngModel
传递给绑定checkboxes
的父组件。
**parent.component.html**
:
<app-checkbox [name]="'CheckBoxRoles'" [ngModel]="name"></app-checkbox>
我无法跟踪所有三个复选框的ngModel
并将它们作为名称/状态传递给一个数组。在checkbox.component.html
中,它本身工作正常,但在父级中却不能。
知道我要去哪里了吗?附言我不想使用:formGroup
选项。