gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:22:04 24 4
gpt4 key购买 nike

所以我在这里使用了指南: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,
value,
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: ['', Validators.required],
description: ['', Validators.required],
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>

关于forms - 如何使用按钮添加更多输入字段 - Angular 2 动态表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41256852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com