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

如何使用按钮添加更多输入字段 – Angular 2动态表单

发布时间:2020-12-17 09:03:24 所属栏目:安全 来源:网络整理
导读:所以我在这里使用了指南: https://angular.io/docs/ts/latest/cookbook/dynamic-form.html 我需要在现有字段中添加更多字段.我做了一些有用的东西,但它很笨重,当它击中它时它重置了形状.代码如下: 在dynamic-form.component.ts中: add_textbox(){ this.qu
所以我在这里使用了指南: https://angular.io/docs/ts/latest/cookbook/dynamic-form.html

我需要在现有字段中添加更多字段.我做了一些有用的东西,但它很笨重,当它击中它时它重置了形状.代码如下:

在dynamic-form.component.ts中:

add_textbox()
{
    this.questions.push(this.questionService.create_textbox({key: "test",label: "Test"}));
    console.log(this.questions);
    this.form = this.qcs.toFormGroup(this.questions);
}

在question.service.ts

create_textbox({key,value,label = '',order = 1,type = "text",description = "",help = ""}: {key?: any,value?: any,label?: any,order?: any,type?: any,description?: any,help?: any})
{
    return new TextboxQuestion({
        key,label,order,description,type
    });
}

我的按钮也在dynamic-form.component.html中,但我希望它在dynamic-form-question.component.ts中.这可能吗?

首先
import { FormGroup,FormArray,FormBuilder,Validators } from '@angular/forms';

然后

addForm: FormGroup; // form group instance

constructor(private formBuilder: FormBuilder) {}
    ngOnInit() { 
        //    *** this is code for adding invoice details ***
         this.addForm = this.formBuilder.group({
            invoice_no: ['',Validators.required],file_no: ['',description: ['',linktodrive: this.formBuilder.array([
                this.initLink(),])
        });
    }
    initLink() {
        return this.formBuilder.group({
            linkAddress: ['',Validators.required]
        });
    }
    addLink() {
        const control = < FormArray > this.addForm.controls['linktodrive'];
        control.push(this.initLink());
    }
    removeLink(i: number) {
        const control = < FormArray > this.addForm.controls['linktodrive'];
        control.removeAt(i);
    }

使用以下命令开始和关闭HTML:

< div formArrayName =“linktodrive”>< / div>

要创建和删除表单的动态字段,请使用以下html:

<div *ngFor="let address of addForm.controls.linktodrive.controls; let i=index">
<div>
<span>Link {{i + 1}}</span>
<span *ngIf="addForm.controls.linktodrive.controls.length > 1"><a (click)="removeLink(i)">REMOVE</a></span>
</div>

<!-- Angular assigns array index as group name by default 0,1,2,... -->
<div [formGroupName]="i">
<input type="text" placeholder="Enter Link" formControlName="linkAddress">
</div>
</div>

最后是“ADD”链接

<div><a (click)="addLink()"></a></div>

(编辑:李大同)

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

    推荐文章
      热点阅读