Datepicker с отклоненным событием изменения ввода - PullRequest
1 голос
/ 19 сентября 2019

Я хочу отправить запрос на мой сервер, чтобы отфильтровать список по дате, выбранной пользователем, но я хочу использовать для этого отладку, чтобы не спамить серверную часть.

Мой компонент TS

@ViewChild('searchInputDateStart', {static: false}) searchInputDateStart: ElementRef;

ngAfterViewInit() {
  fromEvent(this.searchInputDateStart.nativeElement, 'dateInput').pipe(
    map((event: any) => {
      return event.target.value;
  }),
  debounceTime(500)
  ).subscribe((filterValue: string) => {
    this.startDateToFilterFor = filterValue;
    this.sendRequest();
  });
}

Мой шаблон

<mat-form-field appearance="fill"
                          fxFlex.lt-md="20"
                          fxFlex.gt-sm="40"
                          color="accent">
            <input id="inputDateStart"
                   matInput
                   #searchInputDateStart
                   [matDatepicker]="pickerStart">
            <mat-datepicker-toggle matSuffix
                                   [for]="pickerStart"></mat-datepicker-toggle>
            <mat-datepicker #pickerStart></mat-datepicker>

</mat-form-field>

Тот же самый подход работал для события 'keyup' в обычном текстовом поле, точновот так ответ но не для выбора даты

1 Ответ

1 голос
/ 19 сентября 2019

Вот простой способ сделать это:

https://stackblitz.com/edit/angular-s49hsb-gqlydz?file=app/datepicker-overview-example.html

@Component({
  selector: 'datepicker-overview-example',
  templateUrl: 'datepicker-overview-example.html',
  styleUrls: ['datepicker-overview-example.css'],
})
export class DatepickerOverviewExample {
  private date$ = new BehaviorSubject<Date | null>(null);
  private destroy$ = new Subject();

  get date() {
    return this.date$.value;
  }
  set date(value) {
    this.date$.next(value);
  }

  ngOnInit() {
    this.date$.pipe(
      debounceTime(500),
      // you could use a switchMap to cancel any pending requests
      switchMap(date => this.getData(date)), 
      takeUntil(this.destroy$), // stop any pending actions if component is destroyed
    ).subscribe(result => {
      console.log(result);
    });
  }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }

  getData(date: Date) {
    return of('Some http call maybe for ' + date);
  }
}

и в вашем шаблоне:

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date" [(ngModel)]="date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

Вы также можете использовать dateChange событие matDatepicker вместо двусторонней привязки date:

<input matInput [matDatepicker]="picker" placeholder="Choose a date" (dateChange)="date$.next($event.value)">

, поэтому теперь вы можете удалить свойство date в классе компонентов.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...