[Angular] Implement a custom form component by using control value accessor
Angular by value Using Form Component Control Custom
2023-09-14 08:59:18 时间
We have a form component:
<label> <h3>Type</h3> <workout-type formControlName="type" ></workout-type> </label> form = this.fb.group({ name: ['', Validators.required], type: 'strength' }); constructor( private fb: FormBuilder ) {}
the 'type' FormControl will be a custom form element component which refers to 'workout-type' componet.
For the workout-type component:
import {ChangeDetectionStrategy, Component, forwardRef} from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; // Register the control value accessor export const TYPE_CONTROL_ACCESSOR = { provide: NG_VALUE_ACCESSOR, multi: true, useExisting: forwardRef(() => WorkoutTypeComponent) }; @Component({ selector: 'workout-type', providers: [TYPE_CONTROL_ACCESSOR], changeDetection: ChangeDetectionStrategy.OnPush, styleUrls: ['workout-type.component.scss'], template: ` <div class="workout-type"> <div *ngFor="let selector of selectors" [class.active]="selector === value" (click)="setSelected(selector)" class="workout-type__pane"> <img src="/img/{{selector}}.svg" alt="{{selector}}"> <p> {{selector}} </p> </div> </div> ` }) export class WorkoutTypeComponent implements ControlValueAccessor{ selectors = ['strength', 'endurance']; private onTouch: Function; private onModelChange: Function; private value: string; constructor() { } writeValue(value: string): void { this.value = value; } registerOnChange(fn: Function): void { this.onModelChange = fn; } registerOnTouched(fn: Function): void { this.onTouch = fn; } setSelected(value: string): void { this.value = value; this.onModelChange(value); this.onTouch(); } }
相关文章
- 自定义 angular-datetime-picker 格式
- angular框架如何实现父子组件传值、非父子组件传值
- 关于 Angular HTTP Interceptor 中 Request 和 Response 的 immutable 特性
- 前端面试题angular_Vue前端面试题
- uat环境和生产环境的区别_angular 生产环境 相对路径无效
- 关于 Angular 部署以及 index.html 里 base hRef 属性的关联关系
- 使用 Angular Universal 进行服务器端渲染避免 window is not defined 的错误消息
- 【Angular教程】-内容投影u002F@ContentChildu002F@ViewChild
- 关于 Angular 开发时对主流浏览器支持的话题
- 关于 Angular 工程文件 angular.json 里的 inlineCritical 属性
- selenium源码通读·7 |webdriver/common/by.py-By类分析
- 使用 Angular HTTP_INTERCEPTOR 拦截器来记录超时请求的一些思考
- 基于 Spartacus 的 Angular Storefront 性能优化建议
- 微软与 Google 将共同打造 Angular 2
- 基于豆瓣API+Angular开发的webApp
- Angular用来控制元素的展示与否的原生指令介绍