angulartypescriptangular-reactive-formsangular-formsangular-in-memory-web-api

Angular: Issue in adding dynamically generated input field data on the (change) event


I have a feature where I need to send dynamically generated input fields on button click.

I have recreated the problem on stackblitz for better understanding.

In that app, when I enter resourceQuantity, the resourceId fields are dynamically generated. My issue is to identify those fields individually and send them on server side on single button click.

This solution I've found on stackblitz is similar, but in my problem I am not removing or adding on button clicks, but (change) event instead.

Here is the HTML code:

<mat-form-field>
    <input  matInput type="number" formControlName="resourceQuantity" [(ngModel)]="resourceQuantity" placeholder="Enter Resource Quantity" (change)="somethingChanged()"/> 
</mat-form-field><br/><br/>
<div>
    <ul>
        <li *ngFor="let item of counter(resourceQuantity)">
            <input  matInput type="number" placeholder="Enter Resource Number" formControlName="resourceId"/> 
        </li>       
    </ul>
</div>

And here is the TS code:

  ngOnInit() {
    this.form = new FormGroup({
            'employeeId': new FormControl(null, {validators: [Validators.required]}),
            'employeeName': new FormControl(null, {validators: [Validators.required]}),
            'resourceQuantity': new FormControl(null, {validators: [Validators.required]}),
            'resourceId': new FormControl(null, {validators: [Validators.required]})
    });
  }

  somethingChanged() {
      console.log(this.resourceQuantity);
  }

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

Kindly let me know the best solution to my problem. Thanks.


Solution

  • Avoid using ngModel and formControl together. You can make use of formArray along with getter functions in your component to get your result.

    Edit: I have edited my code to reflect the change you requested by subscribing to valueChanges on the resourceQuantity formControl and generating the formArray when it detects the change. This creates the resources in real time.

    Note: Don't forget to unsubscribe from valueChanges to prevent memory leakage. I have updated my Stackblitz to show the same.

    Here is a working example on StackBlitz