Home  >  Article  >  Web Front-end  >  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

青灯夜游
青灯夜游forward
2021-04-28 09:34:592694browse

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.net. If there is any infringement, please contact admin@php.cn delete
Previous article:Detailed explanation of several methods of splitting an array into even blocks in JavaScriptNext article:Detailed explanation of several methods of splitting an array into even blocks in JavaScript

Related articles

See more