


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!

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


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

Atom editor mac version download
The most popular open source editor

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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

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

SublimeText3 Chinese version
Chinese version, very easy to use