Erro no componente mat-date-range-input

Quando clico neste botão

<mat-form-field class="example-form-field" appearance="fill">
          <mat-label>First campaign</mat-label>
          <mat-date-range-input
            [formGroup]="campaignOne"
            [rangePicker]="campaignOnePicker"
            [comparisonStart]="campaignTwo.value.start"
            [comparisonEnd]="campaignTwo.value.end">
            <input matStartDate placeholder="Start date" formControlName="start">
            <input matEndDate placeholder="End date" formControlName="end">
          </mat-date-range-input>
          <mat-hint>MM/DD/YYYY – MM/DD/YYYY</mat-hint>
          <mat-datepicker-toggle matIconSuffix [for]="campaignOnePicker"></mat-datepicker-toggle>
          <mat-date-range-picker #campaignOnePicker></mat-date-range-picker>
        </mat-form-field>

Está dando este erro

core.mjs:6495 ERROR TypeError: date.clone is not a function
    at MomentDateAdapter.clone (material-moment-adapter.mjs:92:21)
    at MomentDateAdapter.getYear (material-moment-adapter.mjs:55:21)
    at MatMonthView._getCellCompareValue (datepicker.mjs:915:44)
    at MatMonthView._setRanges (datepicker.mjs:937:43)
    at MatMonthView._init (datepicker.mjs:823:14)
    at datepicker.mjs:709:35
    at Object.next (Subscriber.js:110:1)
    at SafeSubscriber._next (Subscriber.js:60:1)
    at SafeSubscriber.next (Subscriber.js:31:1)
    at subscribe._OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__.OperatorSubscriber.innerComplete (mergeInternals.js:25:1)

Depedencias

{
  "name": "sistema",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "ng": "ng",
    "start": "ng serve -o --port 4600",
    "build": "ng build",
    "build:hom": "ng build --prod --c=hom",
    "watch": "ng build --watch --configuration development",
    "test": "ng test",
    "lint": "ng lint"
  },
  "dependencies": {
    "@angular/animations": "13.0.1",
    "@angular/cdk": "13.0.0",
    "@angular/common": "13.0.1",
    "@angular/compiler": "13.0.1",
    "@angular/core": "13.0.1",
    "@angular/forms": "13.0.1",
    "@angular/material": "13.0.0",
    "@angular/material-moment-adapter": "13.0.0",
    "@angular/platform-browser": "13.0.1",
    "@angular/platform-browser-dynamic": "13.0.1",
    "@angular/router": "13.0.1",
    "@ngneat/transloco": "3.1.0",
    "@stomp/stompjs": "^6.1.0",
    "angular2-text-mask": "^9.0.0",
    "apexcharts": "3.29.0",
    "crypto-js": "3.3.0",
    "highlight.js": "11.3.1",
    "lodash-es": "4.17.21",
    "moment": "2.29.1",
    "ng-apexcharts": "1.5.12",
    "ng-brazil": "^2.4.5",
    "ng-recaptcha": "^9.0.0",
    "ng2-pdf-viewer": "^6.4.1",
    "ngx-currency": "^2.5.3",
    "ngx-markdown": "13.0.0",
    "ngx-mat-select-search": "^3.2.0",
    "ngx-material-file-input": "^3.0.0",
    "ngx-quill": "16.0.1",
    "ngx-toastr": "^13.2.1",
    "ngx-webstorage": "^9.0.0",
    "perfect-scrollbar": "1.5.3",
    "primeicons": "^4.1.0",
    "primeng": "^11.0.0-rc.1",
    "quill": "1.3.7",
    "rxjs": "7.4.0",
    "sockjs-client": "^1.5.1",
    "tslib": "2.3.1",
    "zone.js": "0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "13.0.2",
    "@angular-eslint/builder": "12.6.1",
    "@angular-eslint/eslint-plugin": "12.6.1",
    "@angular-eslint/eslint-plugin-template": "12.6.1",
    "@angular-eslint/schematics": "12.6.1",
    "@angular-eslint/template-parser": "12.6.1",
    "@angular/cli": "13.0.2",
    "@angular/compiler-cli": "13.0.1",
    "@tailwindcss/aspect-ratio": "0.3.0",
    "@tailwindcss/line-clamp": "0.2.2",
    "@tailwindcss/typography": "0.4.1",
    "@types/chroma-js": "2.1.3",
    "@types/crypto-js": "3.1.47",
    "@types/highlight.js": "10.1.0",
    "@types/jasmine": "3.10.2",
    "@types/lodash": "4.14.176",
    "@types/lodash-es": "4.17.5",
    "@types/node": "12.20.37",
    "@typescript-eslint/eslint-plugin": "5.3.1",
    "@typescript-eslint/parser": "5.3.1",
    "autoprefixer": "10.4.0",
    "chroma-js": "2.1.2",
    "eslint": "7.32.0",
    "eslint-plugin-import": "2.25.3",
    "eslint-plugin-jsdoc": "37.0.3",
    "eslint-plugin-prefer-arrow": "1.2.3",
    "jasmine-core": "3.10.1",
    "karma": "6.3.8",
    "karma-chrome-launcher": "3.1.0",
    "karma-coverage": "2.0.3",
    "karma-jasmine": "4.0.1",
    "karma-jasmine-html-reporter": "1.7.0",
    "lodash": "4.17.21",
    "postcss": "8.3.11",
    "tailwindcss": "2.2.19",
    "typescript": "4.4.4"
  }
}

O que pode ser ?

Suspeito que o valor passado para o componente não seja um objeto do moment. Veja se tu consegue imprimir no console os valores que estão envolvidos nesse componente.

Pelo que vi, a função clone é do moment: Moment Clone - momentjs.com


Acredito que vc tenha que ter um objeto do tipo Moment sendo usado no componente para funcionar. Com isso, a função cloneserá reconhecida.

Mas utilizei conforme exemplo:

1 curtida

Posta o código do form no componente pra gente ver.

Fiz assim:

import {
  ChangeDetectorRef,
  Component,
  ElementRef,
  ViewChild,
  ViewEncapsulation,
} from "@angular/core";
import { FormControl, FormGroup } from "@angular/forms";
import { MatPaginator, PageEvent } from "@angular/material/paginator";
import { MatSort } from "@angular/material/sort";
import { MatTableDataSource } from "@angular/material/table";
import { ActivatedRoute, Router } from "@angular/router";
import { fuseAnimations } from "@fuse/animations";
import { FuseMediaWatcherService } from "@fuse/services/media-watcher";
import { NUMERO_INICIAL_PESQUISA } from "app/core/api/erp.api";
import { StateStorageService } from "app/core/auth/state-storage.service";
import { DefaultManterComponent } from "app/core/classes/default.manter.component";
import { AppConfig } from "app/core/config/app.config";
import { Layout } from "app/layout/layout.types";
import { environment } from "environments/environment";
import { merge, of as observableOf, Subject } from "rxjs";
import {
  catchError,
  map,
  startWith,
  switchMap,
  takeUntil,
} from "rxjs/operators";

@Component({
  selector: "configuracao",
  templateUrl: "./configuracao.component.html",
  styles: [
    `
      .configuracao-grid {
        grid-template-columns: 48px auto 40px;

        @screen sm {
          grid-template-columns: 48px auto 112px 72px;
        }

        @screen md {
          grid-template-columns: 48px 112px auto 112px 72px;
        }

        @screen lg {
          grid-template-columns: 48px 112px auto 112px 96px 96px 72px;
        }
      }
    `,
  ],
  encapsulation: ViewEncapsulation.None,
  animations: fuseAnimations,
})
export class ConfiguracaoComponent extends DefaultManterComponent {
  rota = "configuracao/";
  urlBase = "configuracao";
  nomePagina = "Configuração";
  environmentBackend = environment.SITE;
  numeroPaginaInicial: number = NUMERO_INICIAL_PESQUISA;
  pesquisa: any;
  lista: any[];
  dataSource: MatTableDataSource<any> = new MatTableDataSource();
  @ViewChild(MatPaginator, { static: true })
  paginator: MatPaginator;
  @ViewChild("filter", { static: true })
  filter: ElementRef;
  @ViewChild(MatSort, { static: true })
  sort: MatSort;
  mostrarPesquisa: boolean;
  resultsLength: number;
  isLoadingResults: boolean;
  isRateLimitReached: boolean;
  entidades: any[];
  private _unsubscribeAll: Subject<any> = new Subject<any>();
  colunas: string[] = [
    "diaAtraso",
    "periodoGratuidade",
    "vencimentoBoleto",
    "dataHoraCadastro",
  ];
  config: AppConfig;
  layout: Layout;
  scheme: "dark" | "light";
  theme: string;
  themes: [string, any][] = [];
  pesquisaBanco: any;
  formGroup = new FormGroup({
    diaAtraso: new FormControl(),
    periodoGratuidade: new FormControl(),
    vencimentoBoleto: new FormControl(),
  });
  formGroupPesquisar = new FormGroup({
    diaAtraso: new FormControl(),
    periodoGratuidade: new FormControl(),
    vencimentoBoleto: new FormControl(),
  });
  today = new Date();
  month = this.today.getMonth();
  year = this.today.getFullYear();
  campaignOne = new FormGroup({
    start: new FormControl(new Date(this.year, this.month, 13)),
    end: new FormControl(new Date(this.year, this.month, 16)),
  });
  campaignTwo = new FormGroup({
    start: new FormControl(new Date(this.year, this.month, 15)),
    end: new FormControl(new Date(this.year, this.month, 19)),
  });

  constructor(
    protected routaAtual: ActivatedRoute,
    protected router: Router,
    protected stateStorageService: StateStorageService,
    private _changeDetectorRef: ChangeDetectorRef,
    private _fuseMediaWatcherService: FuseMediaWatcherService
  ) {
    super(routaAtual, router, stateStorageService);
  }

  async ngOnInit(): Promise<void> {
    await super.ngOnInit();
    this.pesquisar();
    this._fuseMediaWatcherService.onMediaChange$
      .pipe(takeUntil(this._unsubscribeAll))
      .subscribe(({}) => this._changeDetectorRef.markForCheck());
  }

  async salvar(): Promise<void> {
    this.entidade = {
      ...this.formGroup.value,
    };
    await super.salvar();
    this.pesquisar();
    this.formGroup.reset();
  }

  paginacao(event?: PageEvent): void {
    this.pesquisar(event?.pageIndex, event?.pageSize);
  }

  pesquisar(index = 0, length = this.numeroPaginaInicial) {
    let diaAtraso = 0;
    let periodoGratuidade = 0;
    let vencimentoBoleto = 0;
    if (this.formGroupPesquisar.controls.diaAtraso.value !== null) {
      diaAtraso = this.formGroupPesquisar.controls.diaAtraso.value;
    }
    if (this.formGroupPesquisar.controls.periodoGratuidade.value !== null) {
      periodoGratuidade =
        this.formGroupPesquisar.controls.periodoGratuidade.value;
    }
    if (this.formGroupPesquisar.controls.vencimentoBoleto.value !== null) {
      vencimentoBoleto =
        this.formGroupPesquisar.controls.vencimentoBoleto.value;
    }
    this.pesquisa = {
      paginaAtual: index,
      quantidadeRegistros: length,
      direcao: null,
      campo: null,
      diaAtraso,
      periodoGratuidade,
      vencimentoBoleto,
    };
    this.sort.sortChange.subscribe(() => (this.paginator.pageIndex = 0));
    merge(this.sort.sortChange, this.paginator.page)
      .pipe(
        startWith({}),
        switchMap(() => {
          this.pesquisa.direcao = this.sort.direction;
          this.pesquisa.campo = this.sort.active;
          return this.pesquisaServiceS.pesquisar(
            this.pesquisa,
            this.urlBase,
            this.environmentBackend
          );
        }),
        map((data: any) => {
          this.isLoadingResults = false;
          this.isRateLimitReached = false;
          this.resultsLength = data.body.paginacao.totalElementos;
          return data.body.lista;
        }),
        catchError((error: any) => {
          this.isLoadingResults = false;
          this.isRateLimitReached = true;
          if (error !== "undefined") {
            if (error.error !== null && error.error.texto !== undefined) {
              this.errorServiceS.error(error);
            } else {
              this.errorServiceS.error("Erro em pesquisar um registro !");
            }
          }
          return observableOf([]);
        })
      )
      .subscribe((data: any) => {
        this.entidades = data;
        this.dataSource.data = data;
        this.mostrarPesquisa = true;
      });
  }

  limpar(): void {
    this.formGroupPesquisar.controls.diaAtraso.setValue(0);
    this.formGroupPesquisar.controls.periodoGratuidade.setValue(0);
    this.formGroupPesquisar.controls.vencimentoBoleto.setValue(0);
    this.pesquisaBanco = {
      paginaAtual: 0,
      quantidadeRegistros: this.numeroPaginaInicial,
      direcao: this.sort.direction,
      campo: this.sort.active,
    };
    this.pesquisar();
  }
}

E assim

import {
  ChangeDetectorRef,
  Component,
  ElementRef,
  ViewChild,
  ViewEncapsulation,
} from "@angular/core";
import { FormControl, FormGroup } from "@angular/forms";
import { MatPaginator, PageEvent } from "@angular/material/paginator";
import { MatSort } from "@angular/material/sort";
import { MatTableDataSource } from "@angular/material/table";
import { ActivatedRoute, Router } from "@angular/router";
import { fuseAnimations } from "@fuse/animations";
import { FuseMediaWatcherService } from "@fuse/services/media-watcher";
import { NUMERO_INICIAL_PESQUISA } from "app/core/api/erp.api";
import { StateStorageService } from "app/core/auth/state-storage.service";
import { DefaultManterComponent } from "app/core/classes/default.manter.component";
import { AppConfig } from "app/core/config/app.config";
import { Layout } from "app/layout/layout.types";
import { environment } from "environments/environment";
import { merge, of as observableOf, Subject } from "rxjs";
import {
  catchError,
  map,
  startWith,
  switchMap,
  takeUntil,
} from "rxjs/operators";

const today = new Date();
const month = today.getMonth();
const year = today.getFullYear();

@Component({
  selector: "configuracao",
  templateUrl: "./configuracao.component.html",
  styles: [
    `
      .configuracao-grid {
        grid-template-columns: 48px auto 40px;

        @screen sm {
          grid-template-columns: 48px auto 112px 72px;
        }

        @screen md {
          grid-template-columns: 48px 112px auto 112px 72px;
        }

        @screen lg {
          grid-template-columns: 48px 112px auto 112px 96px 96px 72px;
        }
      }
    `,
  ],
  encapsulation: ViewEncapsulation.None,
  animations: fuseAnimations,
})
export class ConfiguracaoComponent extends DefaultManterComponent {
  rota = "configuracao/";
  urlBase = "configuracao";
  nomePagina = "Configuração";
  environmentBackend = environment.SITE;
  numeroPaginaInicial: number = NUMERO_INICIAL_PESQUISA;
  pesquisa: any;
  lista: any[];
  dataSource: MatTableDataSource<any> = new MatTableDataSource();
  @ViewChild(MatPaginator, { static: true })
  paginator: MatPaginator;
  @ViewChild("filter", { static: true })
  filter: ElementRef;
  @ViewChild(MatSort, { static: true })
  sort: MatSort;
  mostrarPesquisa: boolean;
  resultsLength: number;
  isLoadingResults: boolean;
  isRateLimitReached: boolean;
  entidades: any[];
  private _unsubscribeAll: Subject<any> = new Subject<any>();
  colunas: string[] = [
    "diaAtraso",
    "periodoGratuidade",
    "vencimentoBoleto",
    "dataHoraCadastro",
  ];
  config: AppConfig;
  layout: Layout;
  scheme: "dark" | "light";
  theme: string;
  themes: [string, any][] = [];
  pesquisaBanco: any;
  formGroup = new FormGroup({
    diaAtraso: new FormControl(),
    periodoGratuidade: new FormControl(),
    vencimentoBoleto: new FormControl(),
  });
  formGroupPesquisar = new FormGroup({
    diaAtraso: new FormControl(),
    periodoGratuidade: new FormControl(),
    vencimentoBoleto: new FormControl(),
  });
  campaignOne = new FormGroup({
    start: new FormControl(new Date(year, month, 13)),
    end: new FormControl(new Date(year, month, 16)),
  });
  campaignTwo = new FormGroup({
    start: new FormControl(new Date(year, month, 15)),
    end: new FormControl(new Date(year, month, 19)),
  });

  constructor(
    protected routaAtual: ActivatedRoute,
    protected router: Router,
    protected stateStorageService: StateStorageService,
    private _changeDetectorRef: ChangeDetectorRef,
    private _fuseMediaWatcherService: FuseMediaWatcherService
  ) {
    super(routaAtual, router, stateStorageService);
  }

  async ngOnInit(): Promise<void> {
    await super.ngOnInit();
    this.pesquisar();
    this._fuseMediaWatcherService.onMediaChange$
      .pipe(takeUntil(this._unsubscribeAll))
      .subscribe(({}) => this._changeDetectorRef.markForCheck());
  }

  async salvar(): Promise<void> {
    this.entidade = {
      ...this.formGroup.value,
    };
    await super.salvar();
    this.pesquisar();
    this.formGroup.reset();
  }

  paginacao(event?: PageEvent): void {
    this.pesquisar(event?.pageIndex, event?.pageSize);
  }

  pesquisar(index = 0, length = this.numeroPaginaInicial) {
    let diaAtraso = 0;
    let periodoGratuidade = 0;
    let vencimentoBoleto = 0;
    if (this.formGroupPesquisar.controls.diaAtraso.value !== null) {
      diaAtraso = this.formGroupPesquisar.controls.diaAtraso.value;
    }
    if (this.formGroupPesquisar.controls.periodoGratuidade.value !== null) {
      periodoGratuidade =
        this.formGroupPesquisar.controls.periodoGratuidade.value;
    }
    if (this.formGroupPesquisar.controls.vencimentoBoleto.value !== null) {
      vencimentoBoleto =
        this.formGroupPesquisar.controls.vencimentoBoleto.value;
    }
    this.pesquisa = {
      paginaAtual: index,
      quantidadeRegistros: length,
      direcao: null,
      campo: null,
      diaAtraso,
      periodoGratuidade,
      vencimentoBoleto,
    };
    this.sort.sortChange.subscribe(() => (this.paginator.pageIndex = 0));
    merge(this.sort.sortChange, this.paginator.page)
      .pipe(
        startWith({}),
        switchMap(() => {
          this.pesquisa.direcao = this.sort.direction;
          this.pesquisa.campo = this.sort.active;
          return this.pesquisaServiceS.pesquisar(
            this.pesquisa,
            this.urlBase,
            this.environmentBackend
          );
        }),
        map((data: any) => {
          this.isLoadingResults = false;
          this.isRateLimitReached = false;
          this.resultsLength = data.body.paginacao.totalElementos;
          return data.body.lista;
        }),
        catchError((error: any) => {
          this.isLoadingResults = false;
          this.isRateLimitReached = true;
          if (error !== "undefined") {
            if (error.error !== null && error.error.texto !== undefined) {
              this.errorServiceS.error(error);
            } else {
              this.errorServiceS.error("Erro em pesquisar um registro !");
            }
          }
          return observableOf([]);
        })
      )
      .subscribe((data: any) => {
        this.entidades = data;
        this.dataSource.data = data;
        this.mostrarPesquisa = true;
      });
  }

  limpar(): void {
    this.formGroupPesquisar.controls.diaAtraso.setValue(0);
    this.formGroupPesquisar.controls.periodoGratuidade.setValue(0);
    this.formGroupPesquisar.controls.vencimentoBoleto.setValue(0);
    this.pesquisaBanco = {
      paginaAtual: 0,
      quantidadeRegistros: this.numeroPaginaInicial,
      direcao: this.sort.direction,
      campo: this.sort.active,
    };
    this.pesquisar();
  }
}

Não deu certo

Troquei esta parte

const today = new Date();
const month = today.getMonth();
const year = today.getFullYear();

por esta parte

const today = moment();
const month = today.month();
const year = today.year();

com import moment from “moment”;

Mesmo erro

Alguma ideia do que pode ser ?