简体   繁体   English

如何在Angular4中编写FormBuild for Dynamic输入?

[英]How to write the FormBuild for Dynamic input in Angular4?

This is my .html file. 这是我的.html文件。

<div *ngFor="let q of questions">
                <div class="row">
                    <div class="col-md-12 col-12">
                       <label>{{q.question}}</label>
                    </div>
                    <div class="col-md-12 col-12 q-row">
                        <div class="form-group" [ngClass]="{'has-error':!complexForm.controls['{{q.id}}'].valid && complexForm.controls['{{q.id}}'].touched}">
                            <input class="form-control" type="text"  [formControl]="complexForm.controls['{{q.id}}']">
                           <div *ngIf="complexForm.controls['{{q.id}}'].hasError('required') && complexForm.controls['{{q.id}}'].touched" class="invalid">Please provide your name.</div>
                       </div>
                    </div>
                </div>
            </div>

the variable question can have any length and i am looping it here.I dont know how to write the form build to read the data after submission.please help me?Thanks in advance. 变量问题可以有任何长度,我在这里循环。我不知道如何编写表单构建以在提交后读取数据。请帮助我吗?谢谢。

If you are using template driven approach you have to add ngModel to your input field in order to retrieve the data in your ts file. 如果您使用的是模板驱动方法,则必须在输入字段中添加ngModel才能检索ts文件中的数据。 However this won't work since you'll have many input fields. 但是,这将不起作用,因为您将有许多输入字段。

First you have to set up a reactive form approach in your ts file. 首先,您必须在ts文件中设置反应式表单方法。

Then you need to get the index in your *ngFor. 然后,您需要在* ngFor中获取索引。 Each formControl will be named after this index with [formControlName] 每个formControl将以此索引命名为[formControlName]

    <div 
            class="form-group"
            *ngFor="let q of questions; let i = index">
            <input type="text" name="question" class="form-control" [formControlName]="i">
   </div>

But I'm assuming a lot here. 但我在这里承担很多责任。 It would help if you provide more info about your form and your ts file. 如果您提供有关表格和ts文件的更多信息,将很有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM