加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 使用对象定义定义FomGroup

发布时间:2020-12-17 17:12:09 所属栏目:安全 来源:网络整理
导读:是否可以使用对象定义本机定义ReactiveForm组,而不是直接在组件中定义? 我改为: formEdit = this.fb.group({ id: [null],userName: [{ value: null,disabled: true }],email: [null,Validators.required],name: [null,nickName: [null,Validators.required
是否可以使用对象定义本机定义ReactiveForm组,而不是直接在组件中定义?

我改为:

formEdit = this.fb.group({
  id: [null],userName: [{ value: null,disabled: true }],email: [null,Validators.required],name: [null,nickName: [null,Validators.required]
});

使用类似的东西:

formEdit = this.fb.group(User);

在User类中,我相应地修饰了它的属性.

更新

在User类中定义装饰器会很好,如下所示:

export class User {
    @required
    @disabled
    userName: string;

    @required
    @minValue(0)
    @maxValue(100)
    price: number;

   ...

}

解决方法

我认为你在寻找的是Angular中的 Dynamic Forms.

根据Angular指南:

Building handcrafted forms can be costly and time-consuming,especially if you need a great number of them,they’re similar to each other,and they change frequently to meet rapidly changing business and regulatory requirements.

It may be more economical to create the forms dynamically,based on metadata that describes the business object model.

您必须进行一些可能非常耗时的初始设置.但是一旦得到解决,形式的创建就非常简单.

上面链接的文档有一个很好的指南和用例,其中构建动态表单是有意义的.

更新:

如果您不想更改模板,则必须根据您提供的配置创建一个可以为您生成FormGroup的方法.但同样,这将需要配置而不是POJO.

如果您仍然感兴趣,可以从这里开始:

import { Component } from '@angular/core';
import { FormGroup,FormControl,Validators,FormArray } from '@angular/forms';

@Component({
  selector: 'my-app',templateUrl: './app.component.html',styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  sampleObject = {
    id: { value: null },userName: { value: null,disabled: true },email: { value: null,validators: [Validators.required] },name: { value: null,nickName: { value: null,validators: [Validators.required] }
  };

  formGroup: FormGroup;

  ngOnInit() {
    this.formGroup = new FormGroup(this.createFormGroup(this.sampleObject));
    console.log(this.formGroup);
  }

  private createFormGroup(config) {
    const group = {};
    for(let key in config) {
      const itemConfig = config[key];
      group[key] = new FormControl(itemConfig.value,itemConfig.validators);
    }
    return group;
  }

}

注意:这不适用于所有方案.如果希望它在所有情况下都能工作,则必须相应地改进createFormGroup方法.

Here’s a 07001 for your ref.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读