Struggling to implement two-way binding in Mat-Datepicker

I have included my code snippet below. I am utilizing mat-datepicker and customizing it to function as a year picker. The problem arises when I add

name="control" #control="ngModel" [(ngModel)]=""
to my control, as it throws an error in the console. However, when I remove
name="control" #control="ngModel" [(ngModel)]=""
the control works properly.

    <input class="form-control" name="FDConversationDateYear" #FDConversationDateYear="ngModel" [(ngModel)]="objCompanyFinancialDetails.FDConversationDateYear" [matDatepicker]="dp" placeholder="Month and Year" [formControl]="date" required>

<mat-datepicker-toggle class="datepicker-toggler" matSuffix [for]="dp"></mat-datepicker-toggle>
                                    <mat-datepicker #dp
                                                    startView="multi-year"
                                                    (yearSelected)="chosenYearHandler($event, dp)"
                                                    panelClass="example-month-picker">
                                    </mat-datepicker>

The component.ts file is as follows:

import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
import {MomentDateAdapter} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
import {MatDatepicker} from '@angular/material/datepicker';

import * as _moment from 'moment';
import {default as _rollupMoment, Moment} from 'moment';

const moment = _rollupMoment || _moment;

export const MY_FORMATS = {
  parse: {
    dateInput: 'MM/YYYY',
  },
  display: {
    dateInput: 'YYYY',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'YYYY',
  },
};

@Component({
  selector: 'datepicker-views-selection-example',
  templateUrl: 'datepicker-views-selection-example.html',
  styleUrls: ['datepicker-views-selection-example.css'],
  providers: [
    {provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
    {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
  ],
})
export class DatepickerViewsSelectionExample {
  date = new FormControl(moment());

  chosenYearHandler(normalizedYear: Moment, datepicker: MatDatepicker<Moment>) {
    const ctrlValue = this.date.value;
    ctrlValue.year(normalizedYear.year());
    this.date.setValue(ctrlValue);
  }
}

Here are the errors from my console:

Answer №1

Update your code by removing the formControl attribute if you are utilizing Template Driven Forms:

Here is the revised HTML Code:

<input class="form-control" name="FDConversationDateYear" #FDConversationDateYear="ngModel" [(ngModel)]="date" [matDatepicker]="dp" placeholder="Month and Year" required>
<mat-datepicker-toggle class="datepicker-toggler" matSuffix [for]="dp"></mat-datepicker-toggle>
<mat-datepicker #dp startView="multi-year" (yearSelected)="chosenYearHandler($event, dp)" panelClass="example-month-picker">
</mat-datepicker>

And here is the updated TS Code:

import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';

/** @title Datepicker selected value */
@Component({
  selector: 'datepicker-value-example',
  templateUrl: 'datepicker-value-example.html',
  styleUrls: ['datepicker-value-example.css'],
})
export class DatepickerValueExample {
  date = new Date();
}

Check out the updated code on StackBlitz

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

Tips for ensuring radiobuttons are defaulted to unchecked within a shared form group in Angular 2 and beyond

The radio buttons are linked to data from the database (Web-API). Below are my complete code snippets: component.html <!-- list of Questions --> <div formArrayName="questions"> <!-- <div *ngFor="let que of Questions; let ...

What makes TS unsafe when using unary arithmetic operations, while remaining safe in binary operations?

When it comes to arithmetic, there is a certain truth that holds: if 'a' is any positive real number, then: -a = a*(-1) The Typescript compiler appears to have trouble reproducing arithmetic rules in a type-safe manner. For example: (I) Workin ...

Easy steps for importing node modules in TypeScript

I'm currently navigating the world of TypeScript and attempting to incorporate a module that is imported from a node module. I have chosen not to utilize webpack or any other build tools in order to maintain simplicity and clarity. Here is the struct ...

Nestjs struggles with resolving dependencies

Having trouble finding the issue in my code. (I'm still new to nestjs and trying to learn by working on some apps). The console log is showing the following error: Nest can't resolve dependencies of the UrlsAfipService (?). Please ensure tha ...

Execute a component method once another component has finished loading completely

My setup involves two components that are both being loaded into my <app-root> element as shown below: <app-header [calendarReference]="calendarRef"></app-header> <app-calendar #calendarRef></app-calendar> This is happening ...

A guide on setting a default constructor as a parameter in TypeScript

Through collaboration with a fellow coder on StackOverflow, I have mastered the art of specifying a constructor as an argument to a class: type GenericConstructor<T> = { new(): T; } class MyClass<T> { subclass: T; constructor( SubClas ...

Output specification: Mandate certain attributes of a designated kind, while permitting them to be incomplete

I am searching for a solution in TypeScript that enforces the return type of a method to be a subset of an interface. Essentially, this means that all properties on the returned object must exist on the interface, but they are not required. Background: De ...

Angular 8 feature module routing encompasses various components working together collaboratively

I am currently working on integrating a main module and a feature module that consists of various components. Below, I have provided the configuration for multiple routes within the feature routing file. const priorityRoutes: Routes = [ { path: &a ...

Angular alert: The configuration object used to initialize Webpack does not conform to the API schema

Recently encountered an error with angular 7 that started popping up today. Unsure of what's causing it. Attempted to update, remove, and reinstall all packages but still unable to resolve the issue. Error: Invalid configuration object. Webpack ini ...

Upgrade from AngularJS to the latest version of Angular, version 8

I'm trying to convert this AngularJS code into Angular 2+, but I'm having some trouble. Any ideas on how to do it? I've searched around, but this specific line is confusing me. scope.variable.value = event.color.toHex() Old Code: functi ...

When using Angular and Express together, the session is not continuous as each new request generates a fresh session

Unique Question I have encountered an issue with passport.js while trying to implement authentication in my express application. When I use req.flash('message', 'message content') within a passport strategy, the flashed information see ...

List of nested objects converted into a flat array of objects

Looking to transform a data structure from an array of objects containing objects to an objects in array setup using JavaScript/Typescript. Input: [ { "a": "Content A", "b": { "1": "Content ...

Trouble with React Context State Refreshing

Exploring My Situation: type Props = { children: React.ReactNode; }; interface Context { postIsDraft: boolean; setPostIsDraft: Dispatch<SetStateAction<boolean>>; } const initialContextValue: Context = { postIsDraft: false, setPostIs ...

What is the most effective way to access a variable from a service in all HTML files of Angular 2/4 components?

In my angular 4 project, I have an alert service where all components can set alerts, but only specific components display them in unique locations. My question is: how can I access a variable from this service across all HTML files? The structure of my s ...

The React Component in Next.js does not come equipped with CSS Module functionality

I have been attempting to incorporate and apply CSS styles from a module to a React component, but the styles are not being applied, and the CSS is not being included at all. Here is the current code snippet: ./components/Toolbar.tsx import styles from & ...

Examining the function of a playwright script for testing the capability of downloading files using the window.open

Currently, we are working on a project that uses Vue3 for the frontend and we are writing tests for the application using Playwright. Within our components, there is a download icon that, when clicked, triggers a handler to retrieve a presigned URL from S3 ...

Troubleshooting React Typescript and Bootstrap - Issues with Collapse Component

I've encountered an issue in my React TypeScript app with Bootstrap 5. The app was set up using create-react-app and Bootstrap was added with npm i bootstrap. There is a button in the app that triggers the visibility of some content, following the ex ...

Refresh your webpage automatically using Typescript and Angular

Currently facing an issue and seeking assistance. My query is regarding reloading a website after 5 minutes in a Typescript/Angular application. Can anyone help with this? ...

Encountering the following error message: "E11000 duplicate key error collection"

Currently, I am in the process of developing an ecommerce platform using the MERN stack combined with TypeScript. As part of this project, I am working on a feature that allows users to provide reviews for products. The goal is to limit each user to only o ...

"Ionic 3: Utilizing the If Statement within the subscribe() Function for Increased Results

I added an if conditional in my subscribe() function where I used return; to break if it meets the condition. However, instead of breaking the entire big function, it only breaks the subscribe() function and continues to execute the navCtrl.push line. How ...