search
HomeWeb Front-endJS TutorialDetailed 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.

Detailed explanation of Angular's use of ControlValueAccessor to implement custom form controls

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: &#39;app-test-control-value-accessor&#39;,<br/>  templateUrl: &#39;./test-control-value-accessor.component.html&#39;,<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: &#39;app-root&#39;,<br/>  templateUrl: &#39;./app.component.html&#39;,<br/>  styleUrls: [&#39;./app.component.css&#39;]<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!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use