import { Component } from "@angular/core"; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms"; @Component({ selector: "app-month-select", templateUrl: "./month-select.component.html", styleUrls: ["./month-select.component.less"], providers: [ { provide: NG_VALUE_ACCESSOR, multi: true, useExisting: MonthSelectComponent, }, ], }) export class MonthSelectComponent implements ControlValueAccessor { allMonthChecked = false; indeterminate = false; allMonth = [ { value: 1, label: "一月", checked: false }, { value: 2, label: "二月", checked: false }, { value: 3, label: "三月", checked: false }, { value: 4, label: "四月", checked: false }, { value: 5, label: "五月", checked: false }, { value: 6, label: "六月", checked: false }, { value: 7, label: "七月", checked: false }, { value: 8, label: "八月", checked: false }, { value: 9, label: "九月", checked: false }, { value: 10, label: "十月", checked: false }, { value: 11, label: "十一月", checked: false }, { value: 12, label: "十二月", checked: false }, ]; updateAllMonthChecked() { this.indeterminate = false; if (this.allMonthChecked) { this.allMonth = this.allMonth.map((item) => ({ ...item, checked: true, })); } else { this.allMonth = this.allMonth.map((item) => ({ ...item, checked: false, })); } this.formatVal(); } monthChecked(checked: boolean, value: number) { this.allMonth = this.allMonth.map((i) => (i.value === value ? { ...i, checked } : i)); this.monthCheckEffect(); this.formatVal(); } monthCheckEffect() { if (this.allMonth.every((item) => !item.checked)) { this.allMonthChecked = false; this.indeterminate = false; } else if (this.allMonth.every((item) => item.checked)) { this.allMonthChecked = true; this.indeterminate = false; } else { this.indeterminate = true; } } formatVal() { const vals = this.allMonth.reduce((a, c) => { return c.checked ? a.concat(c.value) : a; }, [] as number[]); this.onChange(vals); } onChange(v: number[]) {} ontouch(v: any) {} writeValue(v: number[]): void { // console.log("v", v); this.allMonth = this.allMonth.map((i) => (v.includes(i.value) ? { ...i, checked: true } : i)); this.monthCheckEffect(); } registerOnChange(fn: any): void { this.onChange = fn; } registerOnTouched(fn: any): void { this.ontouch = fn; } }