Table of Contents
Angular: [ControlValueAccessor] Custom form control
How to implement custom form controls" >How to implement custom form controls
How to use ControlValueAccessor" >How to use ControlValueAccessor
Reference" > Reference
Home Web Front-end JS Tutorial Detailed explanation of Angular's use of ControlValueAccessor to implement custom form controls

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

Apr 28, 2021 am 09:34 AM
angular controlvalueaccessor

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/>
Copy after login

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/>
Copy after login

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/>
Copy after login

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/>
Copy after login

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/>
Copy after login

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 }}


Copy after login
  • 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/>
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Let's talk about metadata and decorators in Angular Let's talk about metadata and decorators in Angular Feb 28, 2022 am 11:10 AM

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!

Detailed explanation of angular learning state manager NgRx Detailed explanation of angular learning state manager NgRx May 25, 2022 am 11:01 AM

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!

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

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

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

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

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

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

Angular + NG-ZORRO quickly develop a backend system Angular + NG-ZORRO quickly develop a backend system Apr 21, 2022 am 10:45 AM

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!

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

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!

A brief analysis of independent components in Angular and see how to use them A brief analysis of independent components in Angular and see how to use them Jun 23, 2022 pm 03:49 PM

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!

See all articles