• angular form set dynamic control(form动态设置control)


    实现效果

    form表单控件的实时更新
    效果如图
    test3

    关键代码

    validateForm: FormGroup;    // 表单校验
    constructor(
        private fb: FormBuilder
    ) { 
        this.validateForm = this.fb.group({
    
        });
    }
    // 这里有一个控件数组,包含控件的显示名称、属性名和控件类型
    this.properties=[
        {nameChain:'account',controlType:0,displayName:'账号'},
        {nameChain:'password',controlType:1,displayName:'密码'},
    ];
    // 先清理之前的控件
    this.validateForm.clearValidators();
    this.properties.forEach(property => {
        // 根据新控件数组,插入控件
        this.validateForm.addControl(property.nameChain, this.fb.control(null, Validators.required));
    });
    

    前端循环properties,填充控件即可

    <form nz-form [formGroup]="validateForm">
        <nz-form-item *ngFor="let property of properties">
            <nz-form-label [nzSm]="2" [nzXs]="2" nzRequired>{{property.displayName}}</nz-form-label>
            <!--输入框-->
            <nz-form-control [nzSm]="4" [nzXs]="4" *ngIf="property.controlType==0">
                <input nz-input [formControlName]="property.nameChain" type="text" class="form-control" name="{{property.nameChain}}" [(ngModel)]="dataObj[property.nameChain]">
            </nz-form-control>
            <!--密码框-->
            <nz-form-control [nzSm]="4" [nzXs]="4" *ngIf="property.controlType==1">
                <input nz-input type="password" [formControlName]="property.nameChain" class="form-control" name="{{property.nameChain}}" [(ngModel)]="dataObj[property.nameChain]">
            </nz-form-control>
            <!--下拉框-->
            <nz-form-control [nzSm]="4" [nzXs]="4" *ngIf="property.controlType==2">
                <nz-select [(ngModel)]="dataObj[property.nameChain]" class="form-control" name="modules" [formControlName]="property.nameChain">
                    <nz-option *ngFor="let city of cities" [nzValue]="city.id" [nzLabel]="city.name">
                    </nz-option>
                </nz-select>
            </nz-form-control>
        </nz-form-item>
    </form>
    

    示例代码

    示例代码

    参考资料

    Angular2 form ControlGroup who hold an undefined number of Control

  • 相关阅读:
    简爱 灵魂所在
    charles抓取http/https
    Class.forName()用法
    ArrayList源码剖析
    java中的多线程
    分布式负载均衡缓冲系统,如何快速定位到是那个服务器
    maven依赖jar包时版本冲突的解决
    简单工厂模式设计(java反射机制改进)
    Fiddler 抓包工具使用详解
    Fiddler 使用
  • 原文地址:https://www.cnblogs.com/Lulus/p/9497872.html
Copyright © 2020-2023  润新知