Home > Enterprise >  How to take value from input which is in *ngFor loop
How to take value from input which is in *ngFor loop

Time:12-22

The problem is that we have to take values that are under *ngFor loop so, it's taking value that is coming from the first input. We have to sore value in an array that is coming from the value of inputs.

HTML

<div *ngFor="let ele of container">
  <div *ngIf="keyValue === ''">
    <input type="text" [(ngModel)]="keyValue" />
    <textarea
      name=""
      id=""
      cols="30"
      rows="10"
      [(ngModel)]="textValue"
    ></textarea>
  </div>
  <button (click)="addContainer()">Add More</button>
</div>

.ts File

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-sample',
  templateUrl: './sample.component.html',
  styleUrls: ['./sample.component.css'],
})
export class SampleComponent implements OnInit {
  constructor() {}
  container: any[] = [0];
  keyValue: String = '';
  textValue: String = '';
  newArray: any = [];
  ngOnInit(): void {}

  addContainer() {
    this.newArray.push({ key: this.keyValue, values: this.textValue });
    console.log(this.newArray);

    this.container.push(this.container.length);
    console.log(this.container);
  }
}

CodePudding user response:

You should be using reactive form to build forms, if for a very simple form you want to create it like this.

HTML:

<div *ngFor="let ele of container; let i = index">

  <div >
    <input type="text" [(ngModel)]="newArray[i].values" />
    <textarea
      name=""
      id=""
      cols="30"
      rows="10"
      [(ngModel)]="newArray[i].textValue"
    ></textarea>
  </div>
</div>
<button (click)="addContainer()">Add More</button>

TS:

container: any[] = [1];
  newArray: any = [{ key: 1, values: '' }];
  ngOnInit(): void {}

  addContainer() {
    let keyValue = this.container.length   1;
    this.newArray.push({ key: keyValue, values: '' });
    console.log(this.newArray);

    this.container.push(keyValue);
    console.log(this.container);
  }
  • Related