简体   繁体   中英

How to write the FormBuild for Dynamic input in Angular4?

This is my .html file.

<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. 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.

Then you need to get the index in your *ngFor. Each formControl will be named after this index with [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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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