Angular中,自定义表单控件是指非标准控件,例如日期选择器、星级评分等,需要开发者自行创建和封装。下面提供一种简单的实现方法,以自定义星级评分控件为例:
创建控件组件 在控件所在的组件中创建一个新的组件,比如我们把星级评分控件封装在了 StarRatingComponent 组件中。
实现 ControlValueAccessor 在 StarRatingComponent 组件中实现 ControlValueAccessor 接口,这个接口是用来连接 Angular 表单和自定义表单控件的桥梁。在实现 ControlValueAccessor 接口时,我们需要重写一系列方法,分别用来读取和写入表单模型值、控制表单的禁用状态、注册表单change和touched事件等。下面是一个简单的例子:
import { Component, forwardRef, Input } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({ selector: 'app-star-rating', templateUrl: './star-rating.component.html', styleUrls: ['./star-rating.component.css'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => StarRatingComponent), multi: true } ] }) export class StarRatingComponent implements ControlValueAccessor { @Input() disabled: boolean;
rating: number; onChange: (rating: number) => {}; onTouch: () => {};
writeValue(rating: number): void { this.rating = rating; }
registerOnChange(fn: (rating: number) => {}): void { this.onChange = fn; }
registerOnTouched(fn: () => {}): void { this.onTouch = fn; }
setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; }
updateRating(rating: number): void { if (!this.disabled) { this.rating = rating; this.onChange(rating); this.onTouch(); } } }
这样,在模板中就可以通过 [(ngModel)] 来读取和设置表单模型值,同时也