Angular 如何获取多个复选框的值?
Angular how to get the multiple checkbox values?
我将 Angular 中的复选框用于 select 多个元素,我正在尝试获取该复选框的值以进行提交。
相反,我将这些值作为 true
-s 的数组获取值。
这就是我尝试过的:
export class CreateSessionComponent implements OnInit {
form : FormGroup ;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.form = this.formBuilder.group({
userdata : new FormArray([
new FormControl('', Validators.required)
])
})
}
}
userdata
是从数据库填充的动态数组。
<div formArrayName="useremail; let k = index">
<div *ngFor="let data of userdata">
<div>
<input type="checkbox" name="useremail" formControlName ="{{k}}" [value]="data.email">{{data.email}}
</div>
</div>
</div>
您可以得到检查数据数组:
<input .... (change)="onChange(data)" />
onChange(data){
data.checked = !data.checked;
}
获取所有选中的值
let checkedValues = userdata.filter(x => x.checked).map(x => x.email);
由于您有多个要使用的值,因此需要使用 FormArray
,因为 FormControl
只能捕获一个值。
从声明一个空的 formArray 开始:
this.myForm = this.fb.group({
useremail: this.fb.array([])
});
迭代您的电子邮件,观察更改事件并将相应的电子邮件和事件传递给方法 onChange
,您在其中检查它是否 checked
,然后将相应的电子邮件添加到 formarray ,如果未选中,则从表单数组中删除所选电子邮件:
<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);
}
}
Demo
@AJT_82 答案的问题是,如果您想使用 form.reset() 或 修改模型form.patchValue(),不行。要解决这些问题,您需要实现 ControlValueAccessor 接口。
基本上您需要创建 2 个组件:包含模型值并实现 ControlValueAccessor 的组组件和复选框组件,即实际的复选框。
我写了 a blog post with detailed explanation as well as created a plunker 来演示一些例子。
最终用法:
<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>
组组件的实现:
@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() 调用组组件上的 addOrRemove() 方法,如果复选框的值已经在模型中,则将其删除,否则将其添加到模型中。
我在加载表单自动输入时执行了此功能 select:
[checked]="this.selected? this.selected.type.includes(type) : false"
完整代码:
<label *ngFor="let type of this.entityType" class="checkbox-inline c-checkbox">
<input type="checkbox" [checked]="this.selected? this.selected.type.includes(type) : false" (change)="onChangeEntityType(type, $event.target.checked)"/>
<span class="fa fa-check"></span>{{type | translate}}</label>
哪里
this.selected
是我的对象,
this.selected.type.includes(type)
自动检查复选框是否被选中。
我用两种不同的方法解决了
一个带有简单的复选框数组 - mat-checkbox
另一个带有 mat-selection-list.
post 中的代码要点。
在该值上,您可以设置各种组合。
在我的例子中,我使用了 id 和描述的连接,以便在最后从一个来源初始化表单控件..
我的问题是在一个更简单的示例中清理复选框数组。
没时间浪费了.. 运行 继续下一个任务.. :)
对于Angular 2+检查这个例子link
这是我的方法,我将其用于 ionic cordova 联系人插件以从地址簿中获取多个联系人并添加所选联系人。
HTML
<div *ngFor="let c of addressBook" tappable class="px-2">
<input type="checkbox" (change)="onChangeContact($event,c)">
<p>{{ c.displayName }}</p>
</div>
TS
onChangeContact($event, c) {
if ($event.target.checked) {
this.tempArr.push(c);
} else {
let i: number = 0;
this.tempArr.forEach((item: any) => {
console.log(item);
if (item.displayName == c.displayName) {
this.tempArr.splice(i, 1);
return;
}
i++;
});
}
}
我将 Angular 中的复选框用于 select 多个元素,我正在尝试获取该复选框的值以进行提交。
相反,我将这些值作为 true
-s 的数组获取值。
这就是我尝试过的:
export class CreateSessionComponent implements OnInit {
form : FormGroup ;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.form = this.formBuilder.group({
userdata : new FormArray([
new FormControl('', Validators.required)
])
})
}
}
userdata
是从数据库填充的动态数组。
<div formArrayName="useremail; let k = index">
<div *ngFor="let data of userdata">
<div>
<input type="checkbox" name="useremail" formControlName ="{{k}}" [value]="data.email">{{data.email}}
</div>
</div>
</div>
您可以得到检查数据数组:
<input .... (change)="onChange(data)" />
onChange(data){
data.checked = !data.checked;
}
获取所有选中的值
let checkedValues = userdata.filter(x => x.checked).map(x => x.email);
由于您有多个要使用的值,因此需要使用 FormArray
,因为 FormControl
只能捕获一个值。
从声明一个空的 formArray 开始:
this.myForm = this.fb.group({
useremail: this.fb.array([])
});
迭代您的电子邮件,观察更改事件并将相应的电子邮件和事件传递给方法 onChange
,您在其中检查它是否 checked
,然后将相应的电子邮件添加到 formarray ,如果未选中,则从表单数组中删除所选电子邮件:
<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);
}
}
Demo
@AJT_82 答案的问题是,如果您想使用 form.reset() 或 修改模型form.patchValue(),不行。要解决这些问题,您需要实现 ControlValueAccessor 接口。 基本上您需要创建 2 个组件:包含模型值并实现 ControlValueAccessor 的组组件和复选框组件,即实际的复选框。 我写了 a blog post with detailed explanation as well as created a plunker 来演示一些例子。
最终用法:
<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>
组组件的实现:
@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() 调用组组件上的 addOrRemove() 方法,如果复选框的值已经在模型中,则将其删除,否则将其添加到模型中。
我在加载表单自动输入时执行了此功能 select:
[checked]="this.selected? this.selected.type.includes(type) : false"
完整代码:
<label *ngFor="let type of this.entityType" class="checkbox-inline c-checkbox">
<input type="checkbox" [checked]="this.selected? this.selected.type.includes(type) : false" (change)="onChangeEntityType(type, $event.target.checked)"/>
<span class="fa fa-check"></span>{{type | translate}}</label>
哪里
this.selected
是我的对象,
this.selected.type.includes(type)
自动检查复选框是否被选中。
我用两种不同的方法解决了 一个带有简单的复选框数组 - mat-checkbox 另一个带有 mat-selection-list.
post 中的代码要点。 在该值上,您可以设置各种组合。 在我的例子中,我使用了 id 和描述的连接,以便在最后从一个来源初始化表单控件..
我的问题是在一个更简单的示例中清理复选框数组。 没时间浪费了.. 运行 继续下一个任务.. :)
对于Angular 2+检查这个例子link
这是我的方法,我将其用于 ionic cordova 联系人插件以从地址簿中获取多个联系人并添加所选联系人。
HTML
<div *ngFor="let c of addressBook" tappable class="px-2">
<input type="checkbox" (change)="onChangeContact($event,c)">
<p>{{ c.displayName }}</p>
</div>
TS
onChangeContact($event, c) {
if ($event.target.checked) {
this.tempArr.push(c);
} else {
let i: number = 0;
this.tempArr.forEach((item: any) => {
console.log(item);
if (item.displayName == c.displayName) {
this.tempArr.splice(i, 1);
return;
}
i++;
});
}
}