Angular - 检查多个子组件表单是否为脏的
创始人
2024-10-14 18:02:23
0

在Angular中,可以使用@ViewChildren装饰器来获取多个子组件,并使用FormControldirty属性来检查表单是否被修改。

假设我们有一个父组件ParentComponent,它包含多个子组件ChildComponent,每个子组件都有一个表单控件formControl

首先,在ChildComponent中,我们需要导入FormControlControlValueAccessor,并实现ControlValueAccessor接口的方法。这将使我们能够与FormControl进行交互。

import { Component, forwardRef, OnInit } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => ChildComponent),
      multi: true
    }
  ]
})
export class ChildComponent implements ControlValueAccessor, OnInit {
  formControl: FormControl;
  onChange: any = () => {};
  onTouched: any = () => {};

  constructor() {
    this.formControl = new FormControl();
  }

  ngOnInit() {
    this.formControl.valueChanges.subscribe(() => {
      this.onChange(this.formControl.value);
    });
  }

  writeValue(value: any): void {
    this.formControl.setValue(value);
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
    isDisabled ? this.formControl.disable() : this.formControl.enable();
  }
}

然后,在ParentComponent中,我们可以使用@ViewChildren装饰器来获取所有的ChildComponent实例,并检查它们的formControl是否为脏。

import { Component, ViewChildren, QueryList } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {
  @ViewChildren(ChildComponent) childComponents: QueryList;

  areChildFormsDirty() {
    let dirty = false;
    this.childComponents.forEach(child => {
      if (child.formControl.dirty) {
        dirty = true;
      }
    });
    return dirty;
  }
}

最后,在父组件的模板中,我们可以调用areChildFormsDirty方法来检查多个子组件的表单是否为脏。

子组件表单已修改

这样,我们就可以检查多个子组件表单是否为脏了。

相关内容

热门资讯

记者揭秘!德普之星辅助工具如何... 记者揭秘!德普之星辅助工具如何设置,hhpoker德州真的假的,揭秘教程(有挂软件)1、很好的工具软...
盘点一款!pokemmo手机脚... 盘点一款!pokemmo手机脚本辅助器,wepoker有辅助功能吗,解密教程(有挂辅助);建议优先通...
解密关于!wepoker辅助是... 1、解密关于!wepoker辅助是真的吗,wpk辅助器,AI教程(有挂技巧)。2、wepoker辅助...
推荐攻略!we-poker辅助... 推荐攻略!we-poker辅助,hhpoker有后台操作吗,切实教程(有挂辅助)关于hhpoker有...
每日必备!pokemmo手机版... 每日必备!pokemmo手机版透视脚本,wpk辅助器,透明教程(有挂神器);建议优先通过pokemm...
一分钟揭秘!hhpoker是正... 《一分钟揭秘!hhpoker是正规的吗,wepoker怎么挂底牌,玩家教你(有挂透明)》 hhpok...
我来教教大家!wepoker看... 我来教教大家!wepoker看底牌,约局吧德州可以透视吗,揭秘攻略(有挂透视)1、不需要AI权限,帮...
记者揭秘!epoker透视底牌... 记者揭秘!epoker透视底牌,大菠萝辅助器,2025教程(有挂方法);玩家必备必赢加哟《13670...
教程攻略!pokemmo辅助器... 1、教程攻略!pokemmo辅助器手机版下载,智星德州插件2024最新版,玩家教程(有挂技巧)2、进...
玩家交流!hhpoker必备开... 玩家交流!hhpoker必备开挂,wepoker有没有辅助,微扑克教程(有挂攻略);1分钟了解详细教...