3 回答

TA貢獻2019條經(jīng)驗 獲得超9個贊
由于您要使用多個值,因此需要使用FormArray,因為FormControl只能捕獲一個值。
首先聲明一個空的formArray:
this.myForm = this.fb.group({
useremail: this.fb.array([])
});
迭代您的電子郵件,并查看change事件,并將相應(yīng)的電子郵件和事件傳遞給onChange您檢查方法是否為的方法checked,然后將相應(yīng)的電子郵件添加到formarray,如果未選中,則從表單數(shù)組中刪除所選的電子郵件:
<div *ngFor="let data of emails">
<input type="checkbox" (change)="onChange(data.email, $event.target.checked)"> {{data.email}}<br>
</div>
和onChange:
onChange(email:string, isChecked: boolean) {
const emailFormArray = <FormArray>this.myForm.controls.useremail;
if(isChecked) {
emailFormArray.push(new FormControl(email));
} else {
let index = emailFormArray.controls.findIndex(x => x.value == email)
emailFormArray.removeAt(index);
}
}

TA貢獻1854條經(jīng)驗 獲得超8個贊
如果您想使用form.reset()或form.patchValue()修改模型,則它將無法正常工作。要解決這些問題,您需要實現(xiàn)ControlValueAccessor接口。基本上,您需要創(chuàng)建2個組件:組組件,該組件保存模型值并實現(xiàn)ControlValueAccessor和復選框組件,即實際復選框。我寫了一篇博客文章,上面有詳細的解釋,還創(chuàng)建了一個演示一些示例的插件。
最終用法:
<checkbox-group [(ngModel)]="selectedItems">
<checkbox value="item1">Item 1</checkbox>
<checkbox value="item2">Item 2</checkbox>
<checkbox value="item3">Item 3</checkbox>
<checkbox value="item4">Item 4</checkbox>
</checkbox-group>
組組件的實現(xiàn):
@Component({
selector: 'checkbox-group',
template: `<ng-content></ng-content>`,
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CheckboxGroupComponent),
multi: true
}]
})
export class CheckboxGroupComponent implements ControlValueAccessor {
private _model: any;
// here goes implementation of ControlValueAccessor
...
addOrRemove(value: any) {
if (this.contains(value)) {
this.remove(value);
} else {
this.add(value);
}
}
contains(value: any): boolean {
if (this._model instanceof Array) {
return this._model.indexOf(value) > -1;
} else if (!!this._model) {
return this._model === value;
}
return false;
}
// implementation for add and remove
...
}
復選框組件:
@Component({
selector: 'checkbox',
template: `
<div (click)="toggleCheck()">
<input type="checkbox" [checked]="isChecked()" />
<ng-content></ng-content>
</div>`
})
export class CheckboxComponent {
@Input() value: any;
constructor(@Host() private checkboxGroup: CheckboxGroupComponent) {
}
toggleCheck() {
this.checkboxGroup.addOrRemove(this.value);
}
isChecked() {
return this.checkboxGroup.contains(this.value);
}
}
子復選框控件引用了組組件(@Host()裝飾器)。當復選框被點擊toggleCheck()調(diào)用addOrRemove()方法組部件上,并且如果復選框的值已經(jīng)在模型,它被刪除,否則,它被添加到模型中。
- 3 回答
- 0 關(guān)注
- 723 瀏覽
添加回答
舉報