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方法来检查多个子组件的表单是否为脏。

子组件表单已修改

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

相关内容

热门资讯

事发当天!上饶辅助设备出租,真... 事发当天!上饶辅助设备出租,真是是真的辅助工具(有挂头条)-哔哩哔哩上饶辅助设备出租脚本下载中分为三...
随着!菠萝神辅助器app,一直... 随着!菠萝神辅助器app,一直是有辅助平台(有挂教程)-哔哩哔哩1、很好的工具软件,可以解锁游戏的菠...
推出新举措!兴动海满辅助,一贯... 您好,兴动海满辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在...
做出回应!微乐贵阳捉鸡麻将挂软... 做出回应!微乐贵阳捉鸡麻将挂软件,果然真的是有辅助神器(有挂秘诀)-哔哩哔哩1、打开软件启动之后找到...
反观!九游破解辅助插件,都是真... 反观!九游破解辅助插件,都是真的有辅助神器(有挂秘籍)-哔哩哔哩九游破解辅助插件能透视中分为三种模型...
据文件显示!科米台州麻将辅助,... 据文件显示!科米台州麻将辅助,真是有挂辅助app(竟然有挂)-哔哩哔哩1、每一步都需要思考,不同水平...
今天上午!赣湘互娱挂,总是是有... 今天上午!赣湘互娱挂,总是是有辅助修改器(有挂详情)-哔哩哔哩1、在赣湘互娱挂插件功能辅助器技巧中,...
来临!广西友乐解码器辅助器,原... 来临!广西友乐解码器辅助器,原来真的是有辅助脚本(真的有挂)-哔哩哔哩1.广西友乐解码器辅助器 选牌...
来临!新天道辅助脚本,确实有挂... 来临!新天道辅助脚本,确实有挂辅助下载(有挂秘诀)-哔哩哔哩1、金币登录送、破产送、升级送、活动送。...
近期!青橙竞技卡五星辅助,好像... 近期!青橙竞技卡五星辅助,好像真的是有辅助脚本(竟然有挂)-哔哩哔哩1、用户打开应用后不用登录就可以...