Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | 10x 10x | import { AsyncPipe } from '@angular/common';
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { FieldType, FieldTypeConfig, FormlyAttributes } from '@ngx-formly/core';
import { FormlySelectModule } from '@ngx-formly/core/select';
@Component({
selector: 'formly-field-multicheckbox',
template: `
@for (option of props.options | formlySelectOptions: field | async; track option.value; let i = $index) {
<input type="checkbox"
[id]="id + '_' + i"
[value]="option.value"
[checked]="isChecked(option)"
[formlyAttributes]="field"
[disabled]="formControl.disabled || option.disabled"
(change)="onChange(option.value, $any($event.target).checked)"/>
<label [for]="id + '_' + i">{{ option.label }}</label>
}
`,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
AsyncPipe,
FormlySelectModule,
FormlyAttributes,
],
})
export class FormlyFieldMultiCheckbox extends FieldType<FieldTypeConfig> {
override defaultOptions = {
props: {
formCheck: 'default' as const, // 'default' | 'inline' | 'switch' | 'inline-switch'
},
};
onChange(value: any, checked: boolean) {
this.formControl.markAsDirty();
if (this.props.type === 'array') {
this.formControl.patchValue(checked
? [...(this.formControl.value || []), value]
: [...(this.formControl.value || [])].filter((o) => o !== value),
);
} else {
this.formControl.patchValue({ ...this.formControl.value, [value]: checked });
}
this.formControl.markAsTouched();
}
isChecked(option: any) {
const value = this.formControl.value;
return value && (this.props.type === 'array' ? value.indexOf(option.value) !== -1 : value[option.value]);
}
}
|