'Angular bootstrap how to pick year only from input

I have a simple input in which I have the type of date. I want to pick only year without month date etc.

Right now I am trying this which show with date and month

<input type="date" id="dateDefault" class="form-control" placeholder="Date">


Solution 1:[1]

Well first I would have to say that I would usually use an already created component from a library like Angular Material or PrimeNg but since you go with the raw way there are some things that you need to change.

Using a library, the implementation could be something like this example.

To use raw HTML & Angular you should:

  • Import the DatePipe pipe to your module providers.
  • Add bindings to your component using the ngModel.
  • Transform the month every time the control change. For that you should handle the ngModelChange event.

I implement a simple example to help you understand.

The app.module.ts and the hello.component.ts is the actual implementation

The final implementation could be like this:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'hello',
  template: `
  <input type="date" 
    [ngModel]="selectedDate | date:'yyyy-MM-dd'" 
    (ngModelChange)="onSelectedDateChange($event)" 
    class="form-control" 
    type="date" 
    >

  <pre>selectectedMonth: {{selectedMonth}}</pre>
  
  `,
  styles: [],
})
export class HelloComponent {
  @Input() name: string;

  selectedDate!: Date;
  selectedMonth!: string;

  onSelectedDateChange(value?: string) {
    this.selectedDate = value ? new Date(value) : null;
    this.selectedMonth = this.getMonthAsString(this.selectedDate);
  }

  private getMonthAsString(date: Date) {
    return date?.getMonth ? (date.getMonth() + 1).toString() : '';
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 StPaulis