I am looking to have the datepicker automatically clear when the reset button is clicked

this code snippet is from my component.ts file

resetFilters() {
    this.date = 0;
    this.query.startedAt= null;
    this.query.endedAt=null;
    this.searchTerm = '';
    this.route.params.subscribe((params) => {
      this.machineId = Number(params['id']);
      this.machinesService.getItem(this.machineId).subscribe((response) => {
        this.machineDetails.MachineChanges = response.MachineChanges;
      });
    });
  }

this snippet is from my component.html file

<volante-slottrak-ui-custom-datepicker class="custom-date mb-2"  [placeholder]="'Start Date'"
            [model]="query.startedAt" (modelOutput)="onStartDateChange($event)">
          </volante-slottrak-ui-custom-datepicker>

          <volante-slottrak-ui-custom-datepicker id="test"class="custom-date mb-2" [placeholder]="'End Date'"
            [model]="query.endedAt" (modelOutput)="onEndDateChange($event)">
          </volante-slottrak-ui-custom-datepicker>.

          <button (click)="resetFilters()" class="reset-filters-btn m-r-10 mb-2" id="resetFiltersMealLog">
            <span class="reset-filters-text">Reset All</span>
          </button>

Answer №1

If you want to implement a reset command that can be used in multiple components, one approach is to create a service and use an observable to propagate the reset command. Here's how you can do it:

If you have access to modify the datepicker component files, start by defining a TypeScript interface in a d.ts file:

    export interface DatePickerData{
        date: string,
        startDate: string,
        endDate: string,
        search: string 
    }

Next, create a shared service for both components:

    @Injectable({
      providedIn: 'root'
    })
    export class SharedService {
    private resetRequested$: BehaviorSubject<DatePickerData> = new BehaviorSubject<DatePickerData>(null)
    }

Package your reset data using the defined interface and emit it through the service observable.

Subscribe to this observable in your Datepicker component to react to the incoming data.

If modifying the datepicker files is not an option, consider providing inputs via observables using the async pipe:

    [model]="(endDateObs$ | async)"

Then, trigger the reset values by calling next on these observables. You can manage these observables in a service and reference them directly in your component if needed.

    constructor(
        public service: SharedService
      ) {}
    
    [model]="(service.endDateObs$ | async)"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message: "Angular requires either importing or local installation"

For my ionic application development, I encountered an issue while trying to link pages together in the ionic creator. The error message on the .ts file is: typescript: src/pages/home/home.ts, line: 4 Individual declarations in merged declar ...

Guide on displaying the length of an observable array in an Angular 2 template

I am working with an observable of type 'ICase' which retrieves data from a JSON file through a method in the service file. The template-service.ts file contains the following code: private _caseUrl = 'api/cases.json'; getCases(): Obs ...

Having trouble compiling Angular CLI version 8.3.21 with the command ng serve

Upon trying to compile my first Angular app, I encountered an error when running ng serve: ERROR in ./src/styles.css (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??embedded! ...

Advanced type generics in Typescript

I've hit a roadblock in my attempt to ensure type safety for a function that should take an object and return a number. Despite numerous efforts, I haven't been successful. To give you a simple example (the actual application involves more comple ...

Tips for personalizing the Material UI autocomplete drop-down menu

I'm currently working with Material UI v5 beta1 and I've been attempting to customize the Autocomplete component. My goal is to change the Typography color on the options from black to white when an item is selected. However, I'm struggling ...

An issue arises when trying to access a resolved variable from UI router in a component

I am facing an issue with my UI router state that has a component attached to it: export const exchangeState = { name: 'exchange', url: '/exchange', component: ExchangeMainComponent, resolve: [ { tok ...

Using a Typescript enum as a parameter type can lead to accepting incorrect values

When working with TypeScript, I have defined an enum, and now I want to create a function that accepts a parameter whose value is one of the enum's values. However, TypeScript does not validate the value against the enum, allowing values outside of th ...

Issue with CanActivateChild not being processed

After logging out and navigating to /, I am facing an issue where the canActivateChild guards are not being executed to redirect to the login page. The main requirement is that none of the application should be accessible without first logging in. Below ...

Locating the source and reason behind the [object ErrorEvent] being triggered

I'm facing an issue where one of my tests is failing and the log is not providing any useful information, apart from indicating which test failed... LoginComponent should display username & password error message and not call login when passed no ...

Vue3 with Typescript may either display an error message or remain empty when handling props

I've been attempting to utilize the default Quasar card component in order to display data received from props. Unfortunately, I haven't had any success as my component remains empty and I keep encountering various errors with each attempt. Rece ...

Using Angular2 to perform search functions within the Loopback framework

Can anyone assist me with implementing a "wildcard" query using loopback to search data from the database in my angular2 project? Thank you in advance for your help. This is the query I am trying to use: this.model.find({ "where": { "wildcard ...

Adding an item to a collection using NgRx

I am working with a state that has a specific structure. It consists of a list of Workouts, and each Workout contains a list of exercises associated with it. I have two main objectives: To add new exercises to a particular workout from the existing list o ...

When utilizing Angular2+ InMemoryWebAPI, SVG icons may not load properly

During the setup of InMemoryWebAPI, I encountered an issue where SVG icons were not loading properly. @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule, ReactiveFormsModule, HttpClientModule, H ...

Expand the ApiGateProxyEvent category from aws-lambda

Looking to enhance the ApiGateProxyEvent of aws-lambda in d.ts. Initial attempts replaced the entire APIGatewayProxyEvent instead of extending it as intended. declare namespace AWSLambda { interface APIGatewayProxyEvent { body: any; user: any; ...

Angular 2 forms, popping the chosen item in the `<select>` element

Check out the FormBuilder: let valuesArray = fb.array([ fb.group({ name: 'one' }), fb.group({ name: 'two' }), fb.group({ name: 'three' }), fb.group({ name: 'four' }) ]); this.for ...

Tips for enforcing a mandatory type with TypeScript

Creating a custom type called InputType with optional properties like this: export type InputType = { configJsonUrl?: string; configJsObject?: DataType; rawData?: { [key: string]: string }; action?: () => void; }; export type DataType = { id ...

Exploring the method to retrieve data on the server side through Express when it is shared by the client within a put request

Here is the angular http put request I am working with: sendPutRequest(data) : Observable<any>{ return this.http.put("http://localhost:5050", data).pipe(map(this.handleData)); } After making this call, the server side method being invoked is ...

Ways to utilize/extract data from an enumeration

Hello there! I am currently diving into the world of React and Typescript, eager to expand my knowledge. Please bear with me if my explanations are not up to par. In my react app, I have a scenario where I created an enum that I want to utilize in two diff ...

Angular Multiplexed Templates - Utilizing a Variety of Components

I'm looking to create a Multiple Template scenario, but I could really use some guidance. In this scenario, the User has the ability to change the entire template, meaning they can switch between Template 1, Template 2, Template 3, and so forth. Each ...

Include the circle.css file in the Angular 4 project by loading it in the head section of the

I am currently working with Angular 4 and would like to incorporate the circle.css styles from cssscript. After downloading the file from the provided link, I placed the circle.css within my something component file. However, when attempting to use &l ...