Angular Formly 5.10.3自定义Ionic toggle如何捕获change变更事件
解决方案
第一步:修改自定义Formly组件代码
核心是绑定Ionic toggle的专属ionChange事件(Ionic组件的切换事件不是原生change,这是之前事件不生效的主要原因之一),同时同步状态到Formly表单控制器并主动触发配置的回调函数。
import { Component } from '@angular/core'; import { FieldType } from '@ngx-formly/core'; @Component({ selector: 'formly-field-input', template: ` <span class="toggleContainer"> <p [class]="to.checked ? '' : 'toggleSelected'"> {{ to.textBefore }} </p> <ion-toggle [checked]="to.checked" [disabled]="to.disabled" color="primary" (ionChange)="onToggleChange($event)" > </ion-toggle> <p [class]="to.checked ? 'toggleSelected' : ''"> {{ to.textAfter }} </p> </span> `, styleUrls: ['./toggle-2-labels.component.scss'], }) export class toggle2LabelsComponent extends FieldType { onToggleChange(event: any) { const currentChecked = event.detail.checked; // 同步值到Formly表单控制器 this.formControl.setValue(currentChecked); // 同步更新templateOptions的checked属性 this.to.checked = currentChecked; // 主动触发配置的回调函数 if (typeof this.to.change === 'function') { this.to.change(this.field, event); } if (typeof this.to.onChange === 'function') { this.to.onChange(this.field, currentChecked); } } // 可选:初始化时同步表单控制值到checked属性 ngOnInit() { super.ngOnInit(); if (this.formControl.value != null) { this.to.checked = this.formControl.value; } } }
第二步:验证回调生效
修改完成后,之前在templateOptions里配置的change和onChange回调就可以正常触发了,同时字段对应的exampleName表单值也会自动同步toggle的选中状态。
补充:其他监听状态变更的方案
如果不需要通过templateOptions的回调处理,也可以直接在字段配置的hooks中订阅表单控制器的值变化:
hooks: { onInit: (field: FormlyFieldConfig) => { field.formControl.valueChanges.subscribe((checked) => { console.log('toggle状态变更:', checked); // 这里写业务逻辑 }); //其他业务逻辑 }, }
内容的提问来源于stack exchange,提问作者CVO
相关产品推荐
相关产品推荐

