Here is a method to display a specific string in the mat-datepicker input, while only sending the date in the backend

enter image description hereIn this code snippet, there is a date input field along with a Permanent button. The scenario is that when the Permanent button is clicked, it should display "Permanent" in the input UI (nativeElements value), but the value being sent to the backend is a date 10 years later than the current date. Below is the code snippet:

<ng-container matColumnDef="endsOn">
<mat-header-cell class="m-1" style="max-width: 15%;" *matHeaderCellDef>
    Ends On
</mat-header-cell>
<mat-cell class="m-1" *matCellDef="let element; let i=index">
    <mat-form-field appearance="outline">
        <input #dateInput placeholder="Select Date" matInput [matDatepicker]="picker" [value]="" [formControl]="element.get('END_TIME')" [min]="element.get('START_TIME').value" [max]="moment(element.get('START_TIME').value).add(10,'years').toDate()">
        <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
        <mat-datepicker #picker>
            <mat-datepicker-actions>
                <div class="datepicker-footer" #datepickerFooter>
                    <div class="slider-date__button mt-3">
                        <a mat-button="" style="background-color: #0062cc !important;" class="mat-focus-indicator btn btn-primary d-block w-100 text-white mat-flat-button mat-button-base" tabindex="0" aria-disabled="false" (click)="isPermanentClicked(moment(element.get('START_TIME').value).add(10,'years').toDate(), i)"><span class="mat-button-wrapper">Make Permanent</span><span matripple="" class="mat-ripple mat-button-ripple"></span><span class="mat-button-focus-overlay"></span></a>
                    </div>
                </div>
                <!-- <button mat-button="" style="background-color: #0062cc !important;" class="mat-focus-indicator btn btn-primary d-block w-100 text-white mat-flat-button mat-button-base" tabindex="0" aria-disabled="false" (click)="isPermanentClicked(moment(element.get('START_TIME').value).add(10,'years').toDate(), i)"><span class="mat-button-wrapper">Make Permanent</span><span matripple="" class="mat-ripple mat-button-ripple"></span><span class="mat-button-focus-overlay"></span></button> -->

            </mat-datepicker-actions>
        </mat-datepicker>

    </mat-form-field>
</mat-cell>
</ng-container>

TS -

  isPermanentClicked(permanent , index){
    console.log(index);
    this.dataSource[index].controls['PERMANENT'] = true;
    this.dataSource[index].controls['END_TIME'].setValue(permanent);
    this.dateInput.nativeElement.value = "Permanent"; // only setting for 1st element, I need it to be index specific
    console.log(this.dateInput.nativeElement.value , this.dataSource[index].controls['END_TIME'] );
    this.datepicker.close(); // this is just closing for 1st element and not for others i'e not reachable
 }

The issue mentioned in the second row is that the native element value is not being set to "Permanent."

Answer №1

To handle multiple date inputs, you should utilize viewChildren and then proceed with the same index for executing actions.

export TestComponent implements OnInit {
// define the viewchildren like so
@ViewChildren('dateInput') dateInputs: QueryList<any>;
@ViewChildren('picker') datePickers: QueryList<any>;

isPermanentClicked(permanent , index, dateInput: any, datePicker: any){
    console.log(index);
    this.dataSource[index].controls['PERMANENT'] = true;
    this.dataSource[index].controls['END_TIME'].setValue(permanent);
    this.dateInput.value = "Permanent"; // currently only setting values for 1st element, need to make it index specific
    console.log(this.dateInput.value, this.dataSource[index].controls['END_TIME']);
    this.datePicker.close(); // currently closing for 1st element only, not accessible for others
 }
}

html

<ng-container matColumnDef="endsOn">
<mat-header-cell class="m-1" style="max-width: 15%;" *matHeaderCellDef>
    Ends On
</mat-header-cell>
<mat-cell class="m-1" *matCellDef="let element; let i=index">
    <mat-form-field appearance="outline">
        <input #dateInput placeholder="Select Date" matInput [matDatepicker]="picker" [value]="" [formControl]="element.get('END_TIME')" [min]="element.get('START_TIME').value" [max]="moment(element.get('START_TIME').value).add(10,'years').toDate()">
        <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
        <mat-datepicker #picker>
            <mat-datepicker-actions>
                <div class="datepicker-footer" #datepickerFooter>
                    <div class="slider-date__button mt-3">
                        <a mat-button="" style="background-color: #0062cc !important;" class="mat-focus-indicator btn btn-primary d-block w-100 text-white mat-flat-button mat-button-base" tabindex="0" aria-disabled="false" (click)="isPermanentClicked(moment(element.get('START_TIME').value).add(10,'years').toDate(), i, dateInput, picker)"><span class="mat-button-wrapper">Make Permanent</span><span matripple="" class="mat-ripple mat-button-ripple"></span><span class="mat-button-focus-overlay"></span></a>
                    </div>
                </div>
            </mat-datepicker-actions>
        </mat-datepicker>

    </mat-form-field>
</mat-cell>
</ng-container>

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

Implementing endless scrolling in Angular 5 using data fetched from a httpClient call

Looking to incorporate infinite scroll using a large JSON dataset in Angular 5. The goal is to display the first 5 entries initially, and as the user scrolls, load the next 5. I came across this library: https://github.com/orizens/ngx-infinite-scroll, but ...

angularjs .reject not executing correctly within the then statement

I'm having trouble identifying the bug in my code. For some reason, $q.defer().reject() isn't functioning correctly. defer.resolve works as expected and even reaches the finally segment, but defer.reject (although it doesn't throw an error) ...

Angular 2 RC 4's ViewUtils provider offers a range of functionalities for optimizing views

Is there a way to dynamically load a child component in a parent view? this.viewAddedSubscription = viewManager.viewAdded.subscribe((view) => { let injector = ReflectiveInjector.resolveAndCreate([new Provider('view', { useValue: view })] ...

Locate and retrieve a document by its unique identifier in MongoDB, and then store its information in an array

I am working with two models: Meal and Ingredient. Let's take a look at their schemas: const mealSchema = new Schema({ title: { type: String, required: true }, image: { type: String, required: false }, ingredients: [{ ingredient: { ...

What are the available choices for constructing HTML based on an ajax response?

Are there any alternatives or libraries available for constructing html from an ajax response? Currently, I am taking the json data received, creating the html as a string, and using a jQuery function to insert it into the DOM. However, I believe there mu ...

The Next JS build process is failing to generate certain paths

Issue with Anime Database App Deployment A problem arose when I developed an anime database app using Nextjs and deployed it on Vercel. Although the build was successful and the initial page rendered properly, only a few dynamic routes displayed correctly ...

Is there a way to iterate through an array in reverse, starting from the last element and ending at the first element?

Is there a way in JavaScript to map an Array starting from the last index and going all the way to the beginning descending, without iterating from the beginning index? I'm looking for a more efficient method or feature I might have overlooked. Any s ...

The CSS styles are functioning correctly in index.html, but they are not applying properly in the component.html

When the UI Element is clicked, it should add the class "open" to the list item (li), causing it to open in a collapsed state. However, this functionality does not seem to be working in the xxx.component.html file. Screenshot [] ...

Transform the Nodejs server into a reusable Node module

Can a nodejs API server be transformed into a node module for use in other projects with minimal code modifications? Additional Information: The node js server contains various APIs (get, post, put). If I integrate this server as a node module within anot ...

The link that has been clicked on should remain in an active state

Is there a way to make the link that is clicked on active? I have attempted various scripts but have had no luck in getting the desired effect. Can anyone identify what might be causing the issue? $("a").click(function () { if ($(this).hasClass("acti ...

What advantages does CfnAppSync provide over using AppSync in a CDK project?

We are in the process of enhancing our API by adding new JS resolvers and phasing out the VTL resolvers for an AWS AppSync CDK project, specifically built with Cfn<> Cloud Front CDK. The code snippet below illustrates how this can be achieved: ...

Issue encountered: Failure in automating login through Cypress UI with Keycloak

Struggling with automating an e-commerce store front using Cypress, specifically encountering issues with the login functionality. The authentication and identity tool in use is keycloak. However, the Cypress test fails to successfully log in or register ...

Alan AI does not support installation on React Native

❯ To install the @alan-ai/alan-sdk-react-native package, run: sudo npm i @alan-ai/alan-sdk-react-native --save > Post installation for @alan-ai/contact: > Copying AlanSDK.js, AlanButton.js, and AlanText.js to destination Mak ...

What is the best way to describe duplicate keys within a JSON array?

I have created a specialized program to extract Dungeons and Dragons data from JSON files. While the main functionality is complete, I am struggling with defining unique keys for multiple attack options without manually assigning individual identifiers. H ...

Is it possible for an uninitialized field of a non-null literal string type to remain undefined even with strict null checks in

It seems that there might be a bug in Typescript regarding the behavior described below. I have submitted an issue on GitHub to address this problem, and you can find it at this link. The code example provided in that issue explains the situation more clea ...

Error thrown by webpack: Module 'pug' not found when attempting to access get-api

After setting up webpack in express, a new folder was created. When I try to run bundle.js, it shows the message "server is running on port 3000". However, when I access the API at http://localhost:3000/api/test, the whole bundle.js loads in the console an ...

Effortlessly automate clicking with JavaScript or HTML - learn how now!

Does anyone know how to automatically click a button on a page when it loads? I attempted using this JavaScript code, but it didn't work. <a href="javascript:Clickheretoprint()" id="print"> <script type="text/javascript"> $(document).rea ...

Using Jmeter's JSON Extractor for parsing response and extracting token value

Currently facing an issue with extracting the "webToken" response. I have attempted using both $..webToken and $.webToken as JSON path expressions, but no luck so far. Any suggestions on how to correctly extract this information? This is for use in JMete ...

Using Jquery to make an Ajax request to a PHP script that retrieves JSON data

Hello, I am new to working with JSON. I have a PHP script that contains a multidimensional array, which is then encoded into JSON format like this: <?php header('Content-Type: application/json'); $lista = array ( 'Conoscenti'=&g ...

Trouble with running the "npm run tsc" command in Angular 2 beta

I'm facing an issue with compiling my Typescript using the command npm run ts. What's odd is that I can successfully compile and run it by running npm start. Below is the log: 0 info it worked if it ends with ok 1 verbose cli [ 'node' ...