欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

浅析Angular19 自定义表单控件

程序员文章站 2022-07-04 23:49:31
1 需求 当开发者需要一个特定的表单控件时就需要自己开发一个和默认提供的表单控件用法相似的控件来作为表单控件;自定义的表单控件必须考虑模型和视图之间的数据怎么进行交互...

1 需求

当开发者需要一个特定的表单控件时就需要自己开发一个和默认提供的表单控件用法相似的控件来作为表单控件;自定义的表单控件必须考虑模型和视图之间的数据怎么进行交互

2 官方文档 -> 点击前往

angular为开发者提供了controlvalueaccessor接口来辅助开发者构建自定义的表单控件,开发者只需要在自定义表单控件类中实现controlvalueaccessor接口中的方法就可以实现模型和视图之间的数据交互

interface controlvalueaccessor { 
 writevalue(obj: any): void
 registeronchange(fn: any): void
 registerontouched(fn: any): void
 setdisabledstate(isdisabled: boolean)?: void
}

2.1 writevalue

writevalue(obj: any): void

该方法用于将值写入到自定义表单控件中的元素;

这个参数值(obj)是使用这个自定义表单控件的组件通过模板表单或者响应式表单的数据绑定传过来的;

在自定义表单控件的类中只需要将这个值(obj)赋值给一个成员变量即可,自定义表单控件的视图就会通过属性绑定显示出来这个值

2.2 registeronchange

registeronchange(fn: any): void

自定义表单控件的数据发生变化时会触发registeronchange方法,该方用于如何处理自定义表单控件数据的变化;

registeronchange方法接收的参数(fn)其实是一个方法,该方法负责处理变化的数据

当自定义控件数据变化时就会自动调用fn执行的方法,但是通常的做法是自定义一个方法 propagatechange 让自定义的方法指向fn,这样当数据变化时只需要调用 propagatechange 就可以对变化的数据进行处理

2.3 registerontouched

registerontouched(fn: any): void

表单控件被触摸时会触发registerontouched方法,具体细节待更新......2018-1-31 11:18:33

2.4 setdisabledstate

setdisabledstate(isdisabled: boolean)?: void

待更新......2018-1-31 11:19:30

3 编程步骤

3.1 创建自定义表单控件组件

<div>
 <h4>当前计数为:{{countnumber}}</h4>
 <br />
 <div>
 <button md-icon-button (click)="onincrease()">
  <span>增加</span>
  <md-icon>add</md-icon>
 </button>
 <span style="margin-left: 30px;"></span>
 <button md-icon-button (click)="ondecrease()">
  <span>减少</span>
  <md-icon>remove</md-icon>
 </button>
 </div>
</div>

html

import { component, oninit } from '@angular/core';
import { controlvalueaccessor } from '@angular/forms';
@component({
 selector: 'app-counter',
 templateurl: './counter.component.html',
 styleurls: ['./counter.component.scss']
})
export class countercomponent implements oninit {
 countnumber: number = 0;
 constructor() { }
 ngoninit() {
 }
 onincrease() {
 this.countnumber++;
 }
 ondecrease() {
 this.countnumber--;
 }
}

3.1.1 功能描述

点击增加按钮时当前计数会增加1,点击减少按钮时当前计数会剪1

浅析Angular19 自定义表单控件 

3.1.2 直接在其他组件中使用时会报错

浅析Angular19 自定义表单控件 

报错信息如下:

浅析Angular19 自定义表单控件 

错误信息是说我们我们使用的组件<app-counter>还不是一个表单控件

3.2 如何让<app-counter>组件变成一个表单控件组件

3.2.1 实现 controlvalueaccessor 接口

浅析Angular19 自定义表单控件 

export class countercomponent implements oninit, controlvalueaccessor {
 countnumber: number = 0;
 constructor() { }
 ngoninit() {
 }
 onincrease() {
 this.countnumber++;
 }
 ondecrease() {
 this.countnumber--;
 }
 /**将数据从模型传输到视图 */
 writevalue(obj: any): void {
 }
 /**将数据从视图传播到模型 */
 registeronchange(fn: any): void {
 }
 registerontouched(fn: any): void {
 }
 setdisabledstate?(isdisabled: boolean): void {
 }
}

3.2.2 指定依赖信息providers

浅析Angular19 自定义表单控件 

import { component, oninit, forwardref } from '@angular/core';
import { controlvalueaccessor, ng_value_accessor } from '@angular/forms';
@component({
 selector: 'app-counter',
 templateurl: './counter.component.html',
 styleurls: ['./counter.component.scss'],
 providers: [
 {
  provide: ng_value_accessor,
  useexisting: forwardref(() => countercomponent),
  multi: true
 }
 ]
})
export class countercomponent implements oninit, controlvalueaccessor {
 countnumber: number = 0;
 constructor() { }
 ngoninit() {
 }
 onincrease() {
 this.countnumber++;
 }
 ondecrease() {
 this.countnumber--;
 }
 /**将数据从模型传输到视图 */
 writevalue(obj: any): void {
 }
 /**将数据从视图传播到模型 */
 registeronchange(fn: any): void {
 }
 registerontouched(fn: any): void {
 }
 setdisabledstate?(isdisabled: boolean): void {
 }
}

3.2.3 待修复bug

虽然可以正常运行,但是表单控件中的元素接受不到使用表单控件那个组件中表单模型传过来的数据,表单控件变化的数据也无法回传到使用表单控件那个组件中的表单模型中去;简而言之,就是模型和视图之间无法进行数据交互

3.3 实习那模型和试图的数据交互

3.3.1 模型到视图

重构自定义表单控件类中的 writevalue 方法

技巧01:writevalue 方法中的参数是使用自定义表单控件的那个组件通过表单的数据绑定传进来的

浅析Angular19 自定义表单控件 

3.3.2 视图到模型

》自定义一个方法来处理自定义表单控件中的变化数据

propagatechange = (_: any) => {};

》重构自定义表单控件类中的 registeronchange 方法

 /**将数据从视图传播到模型 */
 registeronchange(fn: any): void {
 this.propagatechange = fn;
 }

》在数据变化的地方调用那个自定义的方法

浅析Angular19 自定义表单控件 

3.4 自定义表单控件组件代码汇总

<div>
 <h4>当前计数为:{{countnumber}}</h4>
 <br />
 <div>
 <button md-icon-button (click)="onincrease()">
  <span>增加</span>
  <md-icon>add</md-icon>
 </button>
 <span style="margin-left: 30px;"></span>
 <button md-icon-button (click)="ondecrease()">
  <span>减少</span>
  <md-icon>remove</md-icon>
 </button>
 </div>
</div>

html

import { component, oninit, forwardref } from '@angular/core';
import { controlvalueaccessor, ng_value_accessor } from '@angular/forms';
@component({
 selector: 'app-counter',
 templateurl: './counter.component.html',
 styleurls: ['./counter.component.scss'],
 providers: [
 {
  provide: ng_value_accessor,
  useexisting: forwardref(() => countercomponent),
  multi: true
 }
 ]
})
export class countercomponent implements oninit, controlvalueaccessor {
 countnumber: number = 0;
 propagatechange = (_: any) => {};
 constructor() { }
 ngoninit() {
 }
 onincrease() {
 this.countnumber++;
 this.propagatechange(this.countnumber);
 }
 ondecrease() {
 this.countnumber--;
 this.propagatechange(this.countnumber);
 }
 /**将数据从模型传输到视图 */
 writevalue(obj: any): void {
 this.countnumber = obj;
 }
 /**将数据从视图传播到模型 */
 registeronchange(fn: any): void {
 /**fn其实是一个函数,当视图中的数据改变时就会调用fn指向的这个函数,从而达到将数据传播到模型的目的 */
 this.propagatechange = fn; // 将fn的指向赋值给this.propagatechange,在需要将改变的数据传到模型时只需要调用this.propagatechange方法即可
 }
 registerontouched(fn: any): void {
 }
 setdisabledstate?(isdisabled: boolean): void {
 }
}

3.5 使用自定义表单控件的那个组件的代码汇总

技巧01:如果自定义表单控件和使用自定义表单控件的组件都在不在同一个模块时需要对自定义表单控件对应组件进行导出和导入操作

浅析Angular19 自定义表单控件 

<div class="panel panel-primary">
 <div class="panel-heading">面板模板</div>
 <div class="panel-body">
 <h3>面板测试内容</h3>
 </div>
 <div class="panel-footer">2018-1-22 10:22:20</div>
</div>

<div class="panel-primary">
 <div class="panel-heading">自定义提取表单控件</div>
 <div class="panel-body">
 <form #myform=ngform>
  <app-counter name="counter" [(ngmodel)]="countnumber">
  </app-counter>
 </form>
 <h6>绿线上是自定义提取的表单控件显示的内容</h6>
 <hr style="border: solid green 2px" />
 <h6>绿线下是使用自定义表单控件时表单的实时数据</h6>
 <h3>表单控件的值为:{{myform.value | json}}</h3>
 </div>
 <div class="panel-footer">2018-1-31 10:09:17</div>
</div>

<div class="panel-primary">
 <div class="panel-heading">提取表单控件</div>
 <div class="panel-body">
 <form #form="ngform">
  <p>outercountervalue value: {{outercountervalue}}</p>
  <app-exe-counter name="counter" [(ngmodel)]="outercountervalue"></app-exe-counter>
  <br />
  <button md-raised-button type="submit">submit</button>
  <br />
  <div>
  {{form.value | json}}
  </div>
 </form>
 </div>
 <div class="panel-footer">2018-1-27 21:51:45</div>
</div>

<div class="panel panel-primary">
 <div class="panel-heading">ngif指令测试</div>
 <div class="panel-body">
 <button md-rasied-button (click)="onchangengifvalue()">改变ngif变量</button>
 <br />
 <div *ngif="ngif; else ngiftrue" >
  <h4 style="background-color: red; color: white" >ngif变量的值为true</h4>
 </div>
 <ng-template #ngiftrue>
  <h4 style="background-color: black; color: white">ngif变量的值为false</h4>
 </ng-template>
 </div>
 <div class="panel-footer">2018-1-27 16:58:17</div>
</div>

<div class="panel panel-primary">
 <div class="panel-heading">rxjs使用</div>
 <div class="panel-body">
 <h4>测试内容</h4>
 </div>
 <div class="panel-footer">2018-1-23 21:14:49</div>
</div>

<div class="panel panel-primary">
 <div class="panel-heading">自定义验证器</div>
 <div class="panel-body">
 <form (ngsubmit)="ontestlogin()" [formgroup]="loginform">
  <md-input-container>
  <input mdinput placeholder="请输入登录名" formcontrolname="username" />
  </md-input-container>
  <br />
  <md-input-container>
  <input mdinput placeholder="请输入密码" formcontrolname="userpwd" />
  </md-input-container>
  <br />
  <button type="submit" md-raised-button>登陆</button>
 </form>
 </div>
 <div class="panel-footer">2018-1-23 11:06:01</div>
</div>

<div class="panel panel-primary">
 <div class="panel-heading">响应式表单</div>
 <div class="panel-body">
 <form [formgroup]="testform">
  <md-input-container>
  <input mdinput type="text" placeholder="请输入邮箱" formcontrolname="email" />
  <span mdsuffix>@163.com</span> 
  </md-input-container>
  <br />
  <md-input-container>
  <input mdinput type="password" placeholder="请输入密码" formcontrolname="password" />
  </md-input-container>
 </form>
 <hr />
 <div>
  <h2>表单整体信息如下:</h2>
  <h4>表单数据有效性:{{testform.valid}}</h4>
  <h4>表单数据为:{{testform.value | json}}</h4>
  <h4>获取单个或多个formcontrol:{{testform.controls['email'] }}</h4>
  <hr />
  <h2>email输入框的信息如下:</h2>
  <h4>有效性:{{testform.get('email').valid}}</h4>
  <h4>email输入框的错误信息为:{{testform.get('email').errors | json}}</h4>
  <h4>required验证结果:{{testform.haserror('required', 'email') | json}}</h4>
  <h4>minlength验证结果:{{ testform.haserror('minlength', 'email') | json }}</h4>
  <h4>hello:{{ testform.controls['email'].errors | json }}</h4>
  <hr />
  <h2>password输入框啊的信息如下:</h2>
  <h4>有效性:{{testform.get('password').valid}}</h4>
  <h4>password输入框的错误信息为:{{testform.get('password').errors | json }}</h4>
  <h4>required验证结果:{{testform.haserror('required', 'password') | json}}</h4>
 </div>
 <div>
  <button nd-rasied-button (click)="ontestclick()">获取数据</button>
  <h4>data变量:{{data}}</h4>
 </div>
 </div>
 <div class="panel-footer">2018-1-22 15:58:43</div>
</div>

<div class="panel panel-primary">
 <div class="panel-heading">利用响应式编程实现表单元素双向绑定</div>
 <div class="panel-body">
 <md-input-container>
  <input mdinput placeholder="请输入姓名(响应式双向绑定):" [formcontrol]="name"/>
 </md-input-container>
 <div>
  姓名为:{{name.value}}
 </div>
 </div>
 <div class="panel-footer">2018-1-22 11:12:35</div>
</div> -->

<div class="panel panel-primary">
 <div class="panel-heading">模板表单</div>
 <div class="panel-body">
 <md-input-container>
  <input mdinput placeholder="随便输入点内容" #a="ngmodel" [(ngmodel)]="desc" name="desc" />
  <button type="button" md-icon-button mdsuffix (click)="ontestngmodelclick()">
  <md-icon>done</md-icon>
  </button>
 </md-input-container>
 <div>
  <h3>名为desc的表单控件的值为:{{ a.value }}</h3>
 </div>
 </div>
 <div class="panel-footer">2018-1-22 10:19:31</div>
</div>

<div class="panel panel-primary">
 <div class="panel-heading">md-chekbox的使用</div>
 <div calss="panel-body">
 <div>
  <md-checkbox #testcheckbox color="primary" checked="true">测试</md-checkbox>
 </div>
 <div *ngif="testcheckbox.checked">
  <h2>测试checkbox被选中啦</h2>
 </div>
 </div>
 <div class="panel-footer">2018-1-18 14:02:20</div>
</div> 

<div class="panel panel-primary">
 <div class="panel-heading">md-tooltip的使用</div>
 <div class="panel-body">
 <span md-tooltip="重庆火锅">鼠标放上去</span>
 </div>
 <div class="panel-footer">2018-1-18 14:26:58</div>
</div>


<div class="panel panel-primary">
 <div class="panel-heading">md-select的使用</div>
 <div class="panel-body">
 <md-select placeholder="请选择目标列表" class="fill-width" style="height: 40px;">
  <md-option *ngfor="let tasklist of tasklists" [value]="tasklist.name">{{tasklist.name}}</md-option>
 </md-select>
 </div>
 <div class="panel-footer">2018-1-18 14:26:58</div>
</div> 

<div class="panel panel-primary">
 <div class="panel-heading">ngnonbindable指令的使用</div>
 <div class="panel-body">
 <h3>描述</h3>
 <p>使用了ngnonbindable的标签,会将该标签里面的元素内容全部都看做时纯文本</p>
 <h3>例子</h3>
 <p>
  <span>{{tasklists | json }}</span>
  <span ngnonbindable>← 这是{{tasklists | json }}渲染的内容</span>
 </p>
 </div>
 <div class="panel-footer">2018-1-19 09:34:26</div>
</div>

html

浅析Angular19 自定义表单控件 

import { component, oninit, hostlistener, inject} from '@angular/core';
import { formcontrol, formgroup, formbuilder, validators } from '@angular/forms';
import { http } from '@angular/http';
import { quoteservice } from '../../service/quote.service';
@component({
 selector: 'app-test01',
 templateurl: './test01.component.html',
 styleurls: ['./test01.component.scss']
})
export class test01component implements oninit {
 countnumber: number = 9;
 outercountervalue: number = 5; 
 ngif = true;
 loginform: formgroup;
 testform: formgroup;
 data: any;
 name: formcontrol = new formcontrol();
 desc: string = 'hello boy';
 tasklists = [
 {label: 1, name: '进行中'},
 {label: 2, name: '已完成'}
 ];
 constructor(
 private formbuilder: formbuilder,
 private http: http,
 @inject('base_config') private baseconfig,
 private quoteservice: quoteservice
 ) {}
 ngoninit() {
 this.testform = new formgroup({
  email: new formcontrol('', [validators.required, validators.minlength(4)], []),
  password: new formcontrol('', [validators.required], [])
 });
 this.name.valuechanges
 .debouncetime(500)
 .subscribe(value => alert(value));
 this.loginform = this.formbuilder.group({
  username: ['', [validators.required, validators.minlength(4), this.myvalidator], []],
  userpwd: ['', [validators.required, validators.minlength(6)], []]
 });
 this.quoteservice.test()
 .subscribe(resp => console.log(resp));
 }
 onchangengifvalue() {
 if (this.ngif == false) {
  this.ngif = true;
 } else {
  this.ngif = false;
 }
 }
 @hostlistener('keyup.enter')
 ontestngmodelclick() {
 alert('提交');
 }
 ontestclick() {
 // this.data = this.testform.get('email').value;
 // console.log(this.testform.geterror);
 console.log(this.testform.controls['email']);
 }
 ontestlogin() {
 console.log(this.loginform.value);
 if (this.loginform.valid) {
  console.log('登陆数据合法');
 } else {
  console.log('登陆数据不合法');
  console.log(this.loginform.controls['username'].errors);
  console.log(this.loginform.get('userpwd').errors);
 }
 }
 myvalidator(fc: formcontrol): {[key: string]: any} {
 const valid = fc.value === 'admin';
 return valid ? null : {myvalidator: {requiredusername: 'admin', actualusername: fc.value}};
 }
}

3.6 初始化效果展示

浅析Angular19 自定义表单控件