Reputation:
I need to set the language for all datepickers in the application when clicking on the corresponding button in another component, example given in the documentation works only in a particular component and I have datepickers in many places so I would not like to add the same logic to each component. Is there any way to do it?
topbar.component.html
<button (click)="changeLanguage('fr')" class="topbar__languageButton" mat-button></button>
<button (click)="changeLanguage('en')" class="topbar__languageButton" mat-button></button>
topbar.component.ts
import { Component, OnInit} from '@angular/core';
import { DateAdapter } from '@angular/material/core';
@Component({
selector: 'app-topbar',
templateUrl: './topbar.component.html',
styleUrls: ['./topbar.component.scss'],
})
export class TopbarComponent implements OnInit {
constructor(private adapter: DateAdapter<any>) { }
ngOnInit(): void {}
changeLanguage(language: string): void {
this.adapter.setLocale(language);
}
}
target.component.html
<mat-form-field appearance="fill">
<mat-label>Choose a date</mat-label>
<input matInput [matDatepicker]="picker">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
target.component.ts
import { Component, OnInit} from '@angular/core';
import { DateAdapter } from '@angular/material/core';
@Component({
selector: 'app-target',
templateUrl: './target.component.html',
styleUrls: ['./target.component.scss'],
})
export class TargetComponent implements OnInit {
constructor() { }
ngOnInit(): void {}
}
Upvotes: 1
Views: 1429
Reputation: 4617
Even though in their example, the MAT_DATE_LOCALE
injection token and also the DateAdapter
are provided at the component level, this does not stop you from having these provided by your root injector in AppModule
. By providing them there, all your components will be getting the same locale settings, unless overriden in another module.
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
CoreModule,
],
providers: [
{ provide: MAT_DATE_LOCALE, useValue: 'de-CH' },
{
provide: DateAdapter,
useClass: MomentDateAdapter,
deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS],
},
{ provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS },
],
bootstrap: [AppComponent],
})
export class AppModule {}
Upvotes: 2