【问题标题】:How to add more input fields using a button - Angular 2 dynamic forms如何使用按钮添加更多输入字段 - Angular 2 动态表单
【发布时间】:2017-05-06 12:39:13
【问题描述】:

所以我在这里使用了指南: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);
}

in 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 中。这可能吗?

【问题讨论】:

    标签: forms angular angular2-forms angular2-formbuilder


    【解决方案1】:

    首先

    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:

    &lt;div formArrayName="linktodrive"&gt;&lt;/div&gt;

    要在表单中创建和删除动态字段,请使用此 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>
    

    最后是“添加”链接

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

    【讨论】:

    • @Stephen Kuehl 我在我的项目中使用了相同的代码。这个对我有用。如果您遇到一些错误,那么您可能做错了什么。这是工作的老板,这就是为什么它有upvote。分享你的错误
    • 错误:找不到带有路径的控件:'0 -> linkAddress'。此错误指向
    • 完整详情请查看此链接scotch.io/tutorials/…。它会帮助你理解:)
    • 你忘了说你需要把HTML包装在&lt;div formArrayName="addresses"&gt;
    • @StephenKuehl 如果您发现缺少某些东西,那么您可以编辑我的答案。我会接受这些改变。它也可以帮助其他程序员。
    【解决方案2】:

    获胜的解决方案可能有点过时了。 使用新的 ng'6 语法的代码看起来或多或少像这样:

    控制器:

    form = this.fb.group({
        title: ['New Project Name'],
        tasks: this.fb.group({
            title: ['Task title XX'],
            content: ['What is this about'],
            **subtasks: this.fb.array([this.initTask()]),**
            points: ['5'],
            hints: ['No hints']
        })
    });
    constructor(private fb: FormBuilder) {}
    
    ngOnInit() {}
    
    onSubmit() {
        console.log(this.form);
    }
    
    initTask() {
        return this.fb.group({
            subtask: ['', Validators.required]
        });
    }
    
    get tasksControl () {
        return this.form.get('tasks') as FormGroup;
    }
    
    get subtaskControl () {
        return this.tasksControl.get('subtasks') as FormArray;
    }
    
    addLink() {
        this.subtaskControl.push(this.initTask());
    }
    removeLink(i: number) {
        this.subtaskControl.removeAt(i);
    }
    

    和这样的html:

    <div formArrayName="subtasks">
        <div *ngFor="let subtask of subtaskControl.controls; let i=index">
            <div [formGroupName]="i">
                <input type="text" placeholder="Enter Link" formControlName="subtask">
            </div>
            <div>
                <a class="btn btn-danger btn-sm" (click)="removeLink(i)">REMOVE</a>
                <a class="btn btn-success btn-sm" (click)="addLink()">Add</a>
            </div>
        </div>
    </div>
    

    【讨论】:

    • 这里我收到此错误 - 错误类型错误:无法在 FormGroupName.get [作为控件] (forms.js:1849) 处读取 null 的属性“getFormGroup”
    【解决方案3】:

    我浏览了一篇非常有用的博客文章,效果很好。 dynamically add rows in reactive forms angular 6。对代码中的任何疑问进行评论

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签