Home > Mobile >  Input change event will not work on input formControl?
Input change event will not work on input formControl?

Time:06-02

<div >
  <input  type="text" placeholder="From"
  [ngxTimepicker]="start" [format]="24"
  formControlName="startTime"
  (change)="startTimeChange($event, i)">
startTimeChange(startTime, i){
  this.orderForm.value.date[i].time.endTime = this.addMinutes(startTime);
  console.log(this.orderForm.value);
}

createItem(): FormGroup {
  return this.formBuilder.group({
    date: [''],
    time: this.formBuilder.group({
      startTime: [''],
      endTime: [''],
    }),
  });
}
addItem(): void {
  this.date = this.orderForm.get('date') as FormArray;
  if (!this.orderForm.value.date[0].date || !this.orderForm.value.date[0].time.startTime || !this.orderForm.value.date[0].time.endTime) {
    this.toastr.error('Please add date & time for continue!');
    this.showError = true;
    return;
  } else {
    this.showError = false;
  }
  this.date.push(this.createItem());
}

Hi, I'm working with angular framework. so maybe anyone experienced this.? when we try to add change event on an input fromControl the change event will not work or cannot be triggered. maybe anyone has other way to add change event on formControl input please let me know. Thanks in advance!!

CodePudding user response:

When using ReactiveForms, you can utilize the FormControl.valueChanges observable directly from your controller to respond to changes.

see: https://angular.io/api/forms/AbstractControl#valueChanges

import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  group: FormGroup;
  constructor(private fb: FormBuilder) {
    this.group = fb.group({example: this.fb.control('')});
    this.group.get('example').valueChanges.subscribe(change => {
      /* changes here */
    })
  }
}

Expanded Example for FormArray

stackblitz: https://stackblitz.com/edit/angular-ivy-y9zi7z?file=src/app/app.component.ts

The idea is similar for FormArray. We simply need slightly more sophistication to manage our subscription since the FormArray may grow over time.

summarized

  • Create the FormGroup, and add it to your FormArray
  • Subscribe to the valueChanges on the relevant controls in the newly created FormGroup
  • Add slightly expanded logic for Subscription cleanup.
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnDestroy {
  form: FormGroup;
  subscribers: Subscription[];

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      parts: this.fb.array([]),
    });
    this.subscribers = [];
  }
}

We will have a form array named parts

Getter

  get partsArray() {
    return (this.form.controls['parts'] as FormArray).controls as FormGroup[];
  }

Template

<div [formGroup]="form">
  <ng-container *ngFor="let grp of partsArray">
    <div  [formGroup]="grp">
      <input type="text" formControlName="start">
      <input type="text" formControlName="end">
    </div>
  </ng-container>
</div>

Add Item to array

  addItem() {
    let array = this.form.get('parts') as FormArray;
    array.push(
      this.fb.group({
        start: this.fb.control(''),
        end: this.fb.control(''),
      })
    );
    this.handleChanges(array.controls[array.length - 1]);
  }

change detection

  handleChanges(control: AbstractControl) {
    this.subscribers.push(
      control.get('end').valueChanges.subscribe((change) => {
        control.get('start').patchValue(change);
      })
    );
  }

For this example I've simply decided to directly set the value of the "start" control to the same value as the "end" control whenever "end" is updated.

cleanup

  ngOnDestroy() {
    this.subscribers.forEach((sub) => {
      if (!sub.closed) sub.unsubscribe();
    });
  }

Because we create a subscription every time we add a row to our form, we may wish to close all these subscriptions when our component is destroyed to avoid leaking memory.

  • Related