簡體   English   中英

我必須在特定循環上添加輸入框,但是當我嘗試添加新輸入框時,它將添加到 angular formarray 中的所有循環中

[英]I have to add input box on particular loop but while i am trying to add new input box , it will add in all the loop in angular formarray

訪問:- https://stackblitz.com/edit/angular-form-array-example-dywppj?file=src/app/app.component.ts

我試圖解決這個問題超過三天但沒有任何解決方案,請幫助我需要做的事情:-我需要在我點擊添加按鈕的特定行上獲取輸入框,但是當我點擊添加按鈕它將在數組的每個索引中添加輸入框。有關更多詳細信息,您可以查看我的 stackblitz 鏈接。

        **********angular formarray ***********
        
        HTML Code :-
       
            <form *ngIf="usersForm" [formGroup]="usersForm" (ngSubmit)="createUsers()">
              <table class="table table-sm table-bordered">
                <thead>
                  <tr class="text-center">
                    <th>Address</th>
                    <th>Phone</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <ng-container *ngFor='let in of counter(this.totalWords) ;let i = index'>  // this is loop for getting automatically some number of input box as per requirment
                  <input class="form-control" type="text" formControlName="name"/>
            
                  <tbody formArrayName="users">
                    <tr *ngFor="let item of usersForm.controls.users.controls; let $index=index" [formGroupName]="$index">
                      <td style="min-width: 120px">
                        <input class="form-control" type="text" formControlName="address"/>
                        <div class="text-danger" *ngIf="usersForm.controls['users'].controls[$index].controls['address'].touched
                                         && usersForm.controls['users'].controls[$index].controls['address'].hasError('required')">
                          Please enter address!
                        </div>
                      </td>
            
                      <td style="min-width: 120px">
                        <input class="form-control" type="text" formControlName="address"/>
                        <div class="text-danger" *ngIf="usersForm.controls['users'].controls[$index].controls['phone'].touched
                                         && usersForm.controls['users'].controls[$index].controls['phone'].hasError('required')">
                          Please enter phone number!
                        </div>
                      </td>
            
                      <td style="width: 100px">
                        <button (click)="addUserRow(i)" class="btn btn-success btn-sm mr-1" type="button">add</button>
                        <button (click)="removeUserRow($index)" class="btn btn-danger btn-sm" type="button">delete</button>
                      </td>
                    </tr>
                  </tbody>
                </ng-container>
            
              </table>
            
              <button (click)="submit()"> submit</button>
            </form>
        
        
        
        ********Typescript Code ************
        
        import { Component } from '@angular/core';
        import { Customer } from './customer.interface';
        import {FormControl,FormGroup,FormArray,FormBuilder,Validators} from '@angular/forms';
        
        @Component({
          selector: 'my-app',
          templateUrl: './app.component.html'
        })
        export class AppComponent {
          usersForm: FormGroup;
          errorMessage: string;
          constructor(private formBuilder: FormBuilder) {
        
          }
          ngOnInit() {
            this.usersForm = this.formBuilder.group({
              name:'',
              users: this.formBuilder.array([
                this.formBuilder.group({
                  address: [null, [Validators.required]],
                  phone: [null, [Validators.required]]
                })
              ])
            });
          }
        
          initUserRow(): FormGroup {
            return this.formBuilder.group({
              address: [null, [Validators.required]],
              phone: [null, [Validators.required]],
            });
          }
        
// Here i am adding input box
          addUserRow(i): void {
        
            const usersArray =
              <FormArray>this.usersForm.controls['users'];
            usersArray.push( this.initUserRow());
          }
       
          submit(){
            console.log(this.usersForm.value)
          }
        
          
          counter(i: number) {
            return new Array(2);
          }
        }
    
    
      [1]: https://i.stack.imgur.com/3Bvkb.png

這是因為您正在使用的表中有兩個*ngFor

第一個:

<ng-container *ngFor='let in of counter(this.totalWords) ;let i = index'>

我不確定你為什么添加這個。 但這按預期工作。 它運行兩次並創建兩個實例,因為您使用過:

counter(i: number) {
            return new Array(2);
          }

現在,您使用了另一個循環來生成 forms,

<tr *ngFor="let item of usersForm.controls.users.controls; let $index=index" [formGroupName]="$index">

由於 parent * ngFor ,它本身基本上有兩個實例。 當你將任何東西推送到它的實例時,它基本上會同時推送由父*ngFor創建的DOM

您可以創建一個實例來解決您的問題。 我不知道為什么它是故意的或者只是一個錯誤。

counter(i: number) {
            return new Array(1); // change to 1
          }

或者我會建議不要使用父*ngFor循環。

但這是重復 forms 的問題。

您仍然可以使用兩個循環來生成 forms 並執行添加和刪除控制功能。

檢查堆棧閃電戰

表單驗證代碼已注釋,您可以基於該方法實現 rest 的功能。

基本上使用可以引用子數組的父數組來推送和彈出它自己的實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM