0

I am trying to develop a feature where the number of input fields generated are decided by the number I input in other input field. For example: If I enter 4 in my 'quantity' form field then 4 input fields for serialNumbers should generate below as list.

My HTML Code:

<mat-form-field>
  <input matInput type="number" formControlName="quantity" placeholder="Enter Quantity" (change)="somethingChanged()" />
</mat-form-field>
<div>
  <ul>
    <li *ngFor="let item of quantity">
      <mat-form-field>
        <input matInput type="number" formControlName="serialNumber" placeholder="Enter Serial Number" />
      </mat-form-field>
    </li>
  </ul>
</div> 

My Component Code:

somethingChanged() {
    let quantity = 0;
    quantity = parseInt(this.form.get('quantity').toString());
    let i = 0;
    while(quantity > 0) {
        this.serialNumber.push();
        i++;
    }
}

As I'm beginner to Angular, I don't get how to catch the onChange event without using Interpolation. Kindly suggest me a solution. Thanks.

1

2 Answers 2

1

try this simple example

quantity: any;
       somethingChanged() {
        console.log(this.quantity)
      }

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

html

 <input  type="number" [(ngModel)]="quantity" placeholder="Enter Quantity" (change)="somethingChanged()"/> 
 <div>
      <ul>
          <li *ngFor="let item of counter(quantity)">
                  <input  type="number" placeholder="Enter Serial Number"/> 
          </li>       
      </ul>
  </div>
Sign up to request clarification or add additional context in comments.

2 Comments

The input fields I'm trying to generate for serialNumbers are supposed to be displayed as list and the quantity is just a number, not a json object. If I enter 2, two input fields should generate below the quantity input. @ORBIT
its genarating exact thing what you want check it
1

Although your question is not clear, I think you need to get a dynamic number of "serialNumbers" from a form. here is the html :

<input type="text" class="form-control" (input)="onNumberChange($event.target.value)">
  <ul *ngIf="items">
   <li *ngFor="let item of items; let i=index">
    {{i}}) <input type="number" [(ngModel)]="serialNumber[i]" class="form-control">
   </li>
  </ul>

and the .ts file should contain:

onNumberChange(numberValue) {  
 this.number = numberValue;
 this.createRange(this.number)
}
    createRange(number){
      for(var i = 1; i <= number; i++){
         this.items.push(i);
      }
}

1 Comment

Could you show me the declaration of items array? In my example, I'm having quantity named form field. Is items same as my quantity form field?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.