angular 定义对象_angular – 使用对象定义定义FomGroup

我认为你在寻找的是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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值