angulartypescriptresetangular-componentsngmodel

Is there a way two reset values from an input component that is rendering twice in Angular?


I've created a Calendar component in Angular that is rendering twice in the parent component with some others inputs. There is a function to reset all the values in the Parent component, so I decided to create another resetting values function in the calendar component and calling it from the parent reset function component through the @ViewChild. Everything works well, but only reset the values for one of the two calendars, and I've tried everything, and I can't figured out what's going on?

Calendar Component:

  @Output() onDateTimeBefore = new EventEmitter();
  @Output() onDateTimeAfter = new EventEmitter();
  
  onDateSelected(date: Date): void {
    const d = new Date();
    const returnedDate = this.isoDateWithoutTimeZone(date);
    this.selectedDate = returnedDate.substring(0, 10);
    if (this.time) {
      this.selectedDate = this.selectedDate + 'T' + this.time + '.000Z';
    } else {
      this.time = this.gettingTime(d);
      this.selectedDate = this.selectedDate + 'T' + this.time + '.000Z';
    }
    this.onDateTimeBefore.emit(this.selectedDate);
    this.onDateTimeAfter.emit(this.selectedDate);
  }

I emit these two different values the parent component, to get them separated with two different functions.

Calendar HTML:

 <mat-form-field class="example-full-width" appearance="outline">
  <mat-label>{{ title }}</mat-label>
  <input
    matInput
    placeholder="{{ title }}"
    [(ngModel)]="selectedDate"
  />
  <button
    class="button-calendar"
    data-testid="button-open"
    matSuffix
    mat-icon-button
    [matMenuTriggerFor]="appMenu"
  >
    <mat-icon>calendar_today</mat-icon>
  </button>
</mat-form-field>

and I pass it to the parent component like this:

<li class="nav-item fl p-2">
  <app-datetime-picker
    (onDateTimeAfter)="choose2($event)"
    [title]="'Created After'"
  ></app-datetime-picker>
</li>
<li class="nav-item fl p-2">
  <app-datetime-picker
    (onDateTimeBefore)="choose($event)"
    [title]="'Created Before'"
  ></app-datetime-picker>
</li>

So as I said before, I just only be able to reset one value of the two components, I reset the values as simple as -> onDateTimeBefore = " " , and onDateTimeAfter = " " . I don't whats going on or what I'm missing here.


Solution

  • You should use ViewChildren if there are multiples as ViewChild will only return the first element.

    ViewChildren returns you a QueryList that you can then call forEach.

    ts

      // Assuming your child component name is DatetimePicker
      @ViewChildren(DatetimePicker) datePickers: QueryList<DatetimePicker>;
    
      clear(date: Date): void {
        this.datePickers.forEach(datePicker => {
          datePicker.clear() // or whatever your clear function is on the child component
        })
      }