How to change the language of a date picker? [duplicate] - javascript

This question already has answers here:
How to use ngx_bootstrap datepicker with frensh version
(3 answers)
Closed 13 days ago.
When I want to select a month, the month is in English. I would like to know how I can change the language to French please?
I guess I need to configure something in the core.module.ts?
#NgModule({
declarations: [],
imports: [
CommonModule,
BrowserModule,
BrowserAnimationsModule,
HttpClientModule,
AppRoutingModule,
ReferenceDataModule,
IdentityModule,
NgxsModule.forRoot(
[AppState, AuthState, ProfileState, ReferenceDataState],
{
developmentMode: !environment.production,
}
),
NgxsStoragePluginModule.forRoot({
key: ["app", "auth", "profile", "referenceData"],
storage: StorageOption.SessionStorage,
}),
BsDropdownModule.forRoot(),
ModalModule.forRoot(),
BsDatepickerModule.forRoot(),
TranslocoRootModule,
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AppHttpInterceptor,
multi: true,
},
{
provide: MODAL_CONFIG_DEFAULT_OVERRIDE,
useValue: NGX_MODAL_OPTIONS,
},
{
provide: BsDatepickerConfig,
useFactory: NGX_DATEPICKER_OPTIONS,
},
],
exports: [AppRoutingModule, TranslocoRootModule],
})
export class CoreModule {}

You can use something like this:
import { BsDatepickerModule, BsLocaleService } from 'ngx-bootstrap/datepicker';
import { defineLocale } from 'ngx-bootstrap/chronos';
import { frLocale } from 'ngx-bootstrap/locale';
defineLocale('fr', frLocale); // <--- define
export class CoreModule {
constructor(private localeService: BsLocaleService) {
this.localeService.use('fr'); // <---- set to default
}
}

you can try this solution
export class AppComponent {
constructor(
private bsLocaleService: BsLocaleService
) {
this.bsLocaleService.use('ar');
}
}
if you are trying to use it inside SharedModule
export class SharedModule {
constructor(
private bsLocaleService: BsLocaleService
) {
this.bsLocaleService.use('fr');
}
}

Related

Uncaught (in promise): Error: No component factory found for MyOpportunitiesFilterPage. Did you add it to #NgModule.entryComponents?

i want to show filter modal when i klik button, the modal is in My-Opportunities-Filter
but there is error "Uncaught (in promise): Error: No component factory found for MyOpportunitiesFilterPage. Did you add it to #NgModule.entryComponents?"
this is my-opportunities.module.ts
#NgModule({
declarations: [
MyOpportunitiesPage,
MyOpportunitiesFilterPage
],
imports: [
IonicPageModule.forChild(MyOpportunitiesPage),
SuperTabsModule
],
exports:[
MyOpportunitiesPage
],
entryComponents: [
MyOpportunitiesFilterPage
],
})
export class MyOpportunitiesPageModule {}
this is my-opportunities.ts
#IonicPage()
#Component({
selector: 'page-my-opportunities',
templateUrl: 'my-opportunities.html',
})
export class MyOpportunitiesPage {
#ViewChild(Content) content: Content;
private filterPage: Modal;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
public dataSerrvice : DataServiceProvider,
private modalCtrl: ModalController
) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad MyOpportunitiesPage');
}
openTransaction() {
this.navCtrl.push('MyOpportunitiesFilterPage');
}
private filter() {
let filterPage: Modal = this.modalCtrl.create(MyOpportunitiesFilterPage, {
});
filterPage.present();
}
this is my-opportunities-filter.module.ts
#NgModule({
declarations: [
MyOpportunitiesFilterPage,
],
imports: [
IonicPageModule.forChild(MyOpportunitiesFilterPage),
],
})
export class MyOpportunitiesFilterPageModule {}
i already add myOpportunitiesFilterPage in declaration, entrycomponets, but it still not works, can u guys help me
i change my-opportunities.module like this, and its works
#NgModule({
declarations: [
MyOpportunitiesPage
//MyOpportunitiesFilterPage
],
imports: [
IonicPageModule.forChild(MyOpportunitiesPage),
SuperTabsModule
],
exports:[
MyOpportunitiesPage
//MyOpportunitiesFilterPage
],
entryComponents: [
MyOpportunitiesPage
//MyOpportunitiesFilterPage
],
providers: [
MyOpportunitiesFilterPage
]
})
export class MyOpportunitiesPageModule {}

not inject my config in core module in angular 8

I have this config file for my project:
import { InjectionToken } from '#angular/core';
import { HttpHeaders } from '#angular/common/http';
export let APP_CONFIG = new InjectionToken<string>('app.config');
export interface IAppConfig {
apiEndpoint: string;
headersOptions: HttpHeaders;
}
export const AppConfig: IAppConfig = {
apiEndpoint: 'https://localhost:44354/',
headersOptions : new HttpHeaders({ 'Content-Type': 'application/json' }),
};
And I'm using core.module:
#NgModule({
declarations: [],
imports: [
CommonModule,
ToastrModule.forRoot()
],
exports: [],
providers: [
{
provide: APP_CONFIG,
useValue: AppConfig
},
{
provide: HTTP_INTERCEPTORS,
useClass: RequestInterceptor, multi: true
}
],
})
export class CoreModule {
constructor( #Optional() #SkipSelf() core: CoreModule) {
if (core) {
throw new Error("CoreModule should be imported ONLY in AppModule.");
}
}
}
And I use it in the app.module and do not inject it in the other module.
For exmaple, I use it in the regster.module for using in service:
constructor(httpClient: HttpClient, #Inject(AppConfig) private appConfig: IAppConfig) {
super(httpClient);
}
But it shows me this error:
>Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[[object Object]]:
What's the problem and how can I sovle it?

APP_INITIALIZER failing test cases

I am using APP_INITIALIZER to make some API calls, everything is working fine but adding
{ provide: APP_INITIALIZER, useFactory: MyProviderFactory, deps: [MyService], multi: true }
in app.module.ts failing my test cases.
Here is my app.module.ts file
import { BrowserModule } from '#angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '#angular/core';
import { RouterModule } from '#angular/router';
import { HttpClientModule } from '#angular/common/http';
import { LayoutModule } from '#angular/cdk/layout';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
// tslint:disable-next-line:max-line-length
import { MyService } from './services/my-provider.service';
export function MyProviderFactory(provider: MyService) {
return () => provider.getdata();
}
#NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule,
BrowserAnimationsModule,
HttpClientModule,
ReactiveFormsModule,
RouterModule.forRoot([
{ path: '', component: AppComponent }
])
],
providers: [ MyService,
{ provide: APP_INITIALIZER, useFactory: MyProviderFactory, deps: [MyService], multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }
Here is the error
"message": "An error was thrown in afterAll\nFailed: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
Also how to test APP_INITIALIZER in the app.
Any help would be appreciated.
As your error says, your factory is not returning a stream (observable, promise, array or iterable). Instead, you are returning a function.
Assuming your MyService.getdata() returns one of those, you can just return it return provider.getdata().

How to inject $templateCache into angular hybrid APP_INITIALIZER hook?

I'm new to Angular5 and TypeScript, so it's very possible it's a simple thing I'm overlooking.
I have an Angular hybrid app that uses ngUpgrade to run AngularJS and Angular5 side-by-side. I'm trying to inject $templateCache into the OnAppInit function so that I can load all the AngularJS HTML templates before the app completely initializes. I'm getting the error "Cannot find name '$templateCacheService'" as indicated below. Is my syntax wrong or is this not possible?
I "upgrade" $templateCache in upgraded-providers.ts like this:
import { InjectionToken, Directive, ElementRef, Injector } from '#angular/core';
import { UpgradeComponent } from '#angular/upgrade/static';
export const $templateCacheService = new InjectionToken<any>('$templateCacheService');
export const $templateCacheServiceProvider = {
provide: $templateCacheService,
useFactory: (i: any) => i.get('$templateCache'),
deps: ['$injector']
};
Then in app.module.ts, I try to inject it into OnAppInit:
import { NgModule, APP_INITIALIZER, Inject } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { MatCommonModule } from '#angular/material';
import { FlexLayoutModule } from '#angular/flex-layout';
import { HttpClientModule, HttpClient, HTTP_INTERCEPTORS } from '#angular/common/http';
import { downgradeInjectable, UpgradeModule, downgradeComponent } from '#angular/upgrade/static';
import { environment } from '../environments/environment';
import {
$templateCacheServiceProvider,
$templateCacheService
} from './upgraded-providers';
import { AppComponent } from './app.component';
import { GlobalVarsService } from './core/global-vars.service';
import { WinAuthInterceptor } from './core/interceptors/win-auth.interceptor';
declare var angular: any;
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatCommonModule,
FlexLayoutModule,
HttpClientModule,
UpgradeModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: WinAuthInterceptor,
multi: true
},
{
provide: APP_INITIALIZER,
useFactory: OnAppInit,
multi: true,
deps: [GlobalVarsService, HttpClient, $templateCacheService]
},
GlobalVarsService,
$templateCacheServiceProvider
]
})
export class AppModule {
constructor(private upgrade: UpgradeModule, private http: HttpClient) { }
ngDoBootstrap() {
angular.module('app').factory('globalVars', downgradeInjectable(GlobalVarsService));
this.upgrade.bootstrap(document.body, ['app'], { strictDi: true });
}
}
////// THIS NEXT LINE GETS error TS2304: Cannot find name '$templateCacheService' /////
export function OnAppInit(globalVars: GlobalVarsService, http: HttpClient, $templateCache: $templateCacheService) {
return (): Promise<any> => {
return new Promise((resolve, reject) => {
http.get(environment.apiBase + '/api/meta/data').subscribe(x => {
globalVars.MetaData = x;
globalVars.VersionNumber = globalVars.MetaData.versionNumber;
globalVars.IsDebugBuild = globalVars.MetaData.isDebugBuild;
globalVars.User = globalVars.MetaData.user;
globalVars.ApiBase = environment.apiBase;
globalVars.Templates.forEach(template => {
$templateCache.put(template.Item1, template.Item2);
});
resolve();
});
});
};
}
This is TypeScript type error, it doesn't affect how the application works (as long as compilation errors are ignored).
templateCacheService is not a valid type here, because $templateCacheService is a variable (injection token), not a type or an interface.
Only Angular class constructors are annotated with types for DI. Since factory functions are annotated with deps property, types in function signature exist only to provide type safety. If it's not needed, types can be skipped:
export function OnAppInit(
globalVars: GlobalVarsService, http: HttpClient,
$templateCache
) { ... }
Otherwise proper types should be used. $templateCache is an object with get, put, etc methods. Appropriate types are provided with AngularJS #types/angular type definitions. It will be something like:
export function OnAppInit(
globalVars: GlobalVarsService, http: HttpClient,
$templateCache: ng.ITemplateCacheService
) { ... }

ngx-translate - check if translation file is available

How do I check if a translation file is available for the result you get from navigator.language using ngx-translate?
I want to do something like:
if( checkLanguageAvailable (navigator.language)) {
this.translate.use( navigator.language );
} else {
this.translate.use( 'en' ); //Default fall back
}
You can use the getLangs() method of ngx-translate to get a list of available languages:
#Component({ ... })
export class MyController {
constructor(private translate: TranslateService) {}
checkLanguageAvailable(lang: string): boolean {
return this.translate.getLangs().includes(lang);
}
}
u can check file exist before use it (make http.get, but this will load file...)
or use missingTranslationHandler, example:
app.module.ts
import ...
export function HttpLoaderFactory(httpClient: HttpClient) {
return new TranslateHttpLoader(httpClient, 'assets/i18n/', '.json');
}
#NgModule({
imports: [
...
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (HttpLoaderFactory),
deps: [HttpClient]
},
isolate: true,
missingTranslationHandler: [{provide: MissingTranslationHandler, useClass: TranslateHandler}]
}),
SimpleNotificationsModule.forRoot()
],
...
TranslateHandler
import {MissingTranslationHandler, MissingTranslationHandlerParams} from '#ngx-translate/core';
export class TranslateHandler implements MissingTranslationHandler {
private response: String;
handle(params: MissingTranslationHandlerParams) {
return 'some translated text'; // here u can return translation
}
}
A better solution:
this.translate.use(navigator.language.split(/-|_/)[0]).toPromise().catch(() => {
this.translate.use('en');
});

Categories

Resources