


Detailed explanation of Angular's use of ControlValueAccessor to implement custom form controls
This article will introduce to you AngularHow to use ControlValueAccessor to implement custom form controls. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Angular: [ControlValueAccessor] Custom form control
In actual development, we usually encounter various For various customized functions, some components will interact with Angular forms. At this time, we usually pass in a FormGroup object from the outside, and then write the corresponding logic inside the component to operate the Angular form. If we only customize one item in the form, it is obviously inappropriate to pass in the entire form object, and the component will also appear bloated.
<form [formGroup]="simpleForm"> <br/> <other-component [form]="simpleForm"></other-component> <br/></form><br/>
So, can we use these custom components like native forms? Currently, the open source component ng-zorro-antd form component can use the formControlName attribute just like the native form. This type of component is called a custom form component. [Related recommendations: "angular Tutorial"]
How to implement custom form controls
In Angular, use ControlValueAccessor can associate components with the outer wrapped form.
ControlValueAccessor is an interface for handling:
- Writing values from the form model to the view/DOM
- Notifying others when the view/DOM changes Form instructions and controls
ControlValueAccessor
The ControlValueAccessor interface defines four methods:
writeValue(obj: any): void<br/><br/>registerOnChange(fn: any): void<br/><br/>registerOnTouched(fn: any): void<br/><br/>setDisabledState(isDisabled: boolean)?: void<br/>
writeValue(obj: any)
: Method to write new values in the form model to the view or DOM properties (if needed), which writes data from the outside to the internal data model. Data flow direction: form model -> component.
registerOnChange(fn: any)
: A way to register a handler that should be called when something in the view changes. It has a function that tells other form directives and form controls to update their values. Usually the event triggering function needs to be saved in registerOnChange. When the data changes, the external data can be notified of the change by calling the event triggering function, and the modified data can be passed as a parameter. Data flow direction: component -> form model.
registerOnTouched(fn: any)
: Register onTouched event, basically the same as registerOnChange, except that this function is used to notify the form component that it is in the touched state and change the internal state of the bound FormControl. Status change: component -> form model.
setDisabledState(isDisabled: boolean)
: When the FormControl change state API is called and the form state changes to Disabled, the setDisabledState() method is called to notify the custom form component of the read status of the current form. Write status. Status change: form model -> component.
How to use ControlValueAccessor
Build a control framework
@Component({<br/> selector: 'app-test-control-value-accessor',<br/> templateUrl: './test-control-value-accessor.component.html',<br/> providers: [{<br/> provide: NG_VALUE_ACCESSOR,<br/> useExisting: forwardRef(() => TestControlValueAccessorComponent),<br/> multi: true<br/> }]<br/>})<br/>export class TestControlValueAccessorComponent implements ControlValueAccessor {<br/><br/> _counterValue = 0;<br/> <br/> private onChange = (_: any) => {};<br/><br/> constructor() { }<br/><br/> get counterValue() {<br/> return this._counterValue;<br/> }<br/><br/> set counterValue(value) {<br/> this._counterValue = value;<br/> // 触发 onChange,component 内部的值同步到 form model<br/> this.onChange(this._counterValue);<br/> }<br/><br/> increment() {<br/> this.counterValue++;<br/> }<br/><br/> decrement() {<br/> this.counterValue--;<br/> }<br/><br/> // form model 的值同步到 component 内部<br/> writeValue(obj: any): void {<br/> if (obj !== undefined) {<br/> this.counterValue = obj;<br/> }<br/> }<br/><br/> registerOnChange(fn: any): void {<br/> this.onChange = fn;<br/> }<br/><br/> registerOnTouched(fn: any): void { }<br/><br/> setDisabledState?(isDisabled: boolean): void { }<br/><br/>}<br/>
Register ControlValueAccessor
In order to get a ControlValueAccessor
for a form control, Angular will internally inject all values registered on the NG_VALUE_ACCESSOR
token, which is what registers the control itself to DI
The frame becomes a control that allows the form to access its value. So, all we need to do is NG_VALUE_ACCESSOR
extend multi-provider with our own value accessor instance (which is our component). So setting multi: true
is to declare that there are many classes corresponding to this token
, scattered everywhere.
Here we must use useExisting
because TestControlValueAccessorComponent
may be created as a directive dependency in the component that uses it. This requires the use of forwardRef
. This function allows us to reference an undefined object.
@Component({<br/> ...<br/> providers: [<br/> { <br/> provide: NG_VALUE_ACCESSOR,<br/> useExisting: forwardRef(() => TestControlValueAccessorComponent ),<br/> multi: true<br/> }<br/> ]<br/>})<br/>export class TestControlValueAccessorComponent implements ControlValueAccessor {<br/> ...<br/>}<br/>
Control interface
- test-control-value-accessor.component.html
<div class="panel panel-primary"><br/> <div class="panel-heading">自定义控件</div><br/> <div class="panel-body"><br/> <button (click)="increment()">+</button><br/> {{counterValue}}<br/> <button (click)="decrement()">-</button><br/> </div><br/></div><br/>
In the form Use
- app.component.html
<div class="constainer"><br/> <form #form="ngForm"><br/> <app-test-control-value-accessor name="message" [(ngModel)]="message"></app-test-control-value-accessor><br/> <button type="button" (click)="submit(form.value)">Submit</button><br/> </form><br/> <pre class="brush:php;toolbar:false">{{ message }}
- app.component.ts
@Component({<br/> selector: 'app-root',<br/> templateUrl: './app.component.html',<br/> styleUrls: ['./app.component.css']<br/>})<br/>export class AppComponent {<br/><br/> message = 5;<br/><br/> submit(value: any): void {<br/> console.log(value);<br/> }<br/><br/>}<br/>
Reference
https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular- 2.html
https://almerosteyn.com/2016/04/linkup-custom-control-to-ngcontrol-ngmodel
https://juejin.im/post/597176886fb9a06ba4746d15
https://github.com/shhdgit/blogs/issues/11
For more programming-related knowledge, please visit: Programming Video! !
The above is the detailed content of Detailed explanation of Angular's use of ControlValueAccessor to implement custom form controls. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



This article continues the learning of Angular, takes you to understand the metadata and decorators in Angular, and briefly understands their usage. I hope it will be helpful to everyone!

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

Do you know Angular Universal? It can help the website provide better SEO support!

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

This article will share with you an Angular practical experience and learn how to quickly develop a backend system using angualr combined with ng-zorro. I hope it will be helpful to everyone!

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

This article will take you through the independent components in Angular, how to create an independent component in Angular, and how to import existing modules into the independent component. I hope it will be helpful to you!
