Date picker in Html is not working as expected - html

I'm working on a requirement where date picker is displayed based on min and max dates when minimum and maximum are provided. But the format shows as attached enter image description here
Requirement is enter image description here
Below is the code snippet i have added HTML and TS.
<mat-form-field>
<input matInput type="date" [min]="todayDate [max]="maxReleaseDate" name='spoDate'
#spoDate="ngModel" [(ngModel)]="newSpoDate" autocomplete="off" required
[disabled]="spoPoCreateDate">
<mat-error *ngIf="spoDate && spoDate.untouched && spoDate.invalid">This is required field
</mat-error>
</mat-form-field>
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { DatePipe } from '#angular/common';
import { Order } from 'app/general-component/models/order';
import { GetService } from 'app/general-component/services/get.service';
import { PostService } from 'app/general-component/services/post.service';
import { environment } from 'environments/environment.prod';
#Component({
selector: 'app-spo-date-popup',
templateUrl: './spo-date-popup.component.html',
styleUrls: ['./spo-date-popup.component.css']
})
export class SpoDatePopupComponent implements OnInit {
currentSpoDate: any;
newSpoDate: any
orderId: any;
selectedOrganization: any;
itemId: any;
orderData: Order;
todayDate: any;
spoCreatePoDateNote: any;
maxReleaseDate: any
orderLineId: any;
currentOrderId: any;
loggedInUser: string;
userGrantList: any;
spoPoCreateDate: boolean;
constructor(private route: ActivatedRoute, private getService: GetService, private postService: PostService, private datePipe: DatePipe) { }
ngOnInit(): void {
let date = this.datePipe.transform(new Date(), 'dd/MM/yyyy');
this.todayDate = (date as string).split('/').reverse().join('-');
this.route.queryParams.subscribe(
(params) => {
this.orderId = params["orderId"];
this.selectedOrganization = params["selectedOrganization"];
this.itemId = params["ItemId"];
this.orderLineId = params["OrderLineId"];
this.currentOrderId = params["OrderId"];
this.loggedInUser = params["loggedInUser"]
},
(error) => console.log("error" + error)
)
this.grantCheck();
this.getService.getData(environment.getOrderByIdURL + this.currentOrderId, this.selectedOrganization).subscribe(res => {
this.orderData = res as Order;
if (this.orderData) {
this.orderData.OrderLine.forEach((e) => {
if (this.orderLineId === e.OrderLineId) {
this.currentSpoDate = e.Extended.PODropDate ? e.Extended.PODropDate : "";
this.maxReleaseDate = e.Extended.ReleaseDate ? this.datePipe.transform(new Date(e.Extended.ReleaseDate), 'yyy-MM-dd') : "";
console.log("SPOPODATEPOPUP :: ", this.maxReleaseDate);
}
})
}
});
let configData = {};
this.getService.getData(`${environment.configStoreURL}/REST_EX01`, this.selectedOrganization).subscribe((res) => {
let REST_EX01_CONFIG = res.ConfigStoreData;
if (res.ConfigStoreData) {
let list = REST_EX01_CONFIG.split(';');
list.forEach(e => {
let ex01Configs = e.split('=');
configData = {
...configData,
[ex01Configs[0]]: ex01Configs[1]
}
})
// #ts-ignore
this.spoCreatePoDateNote = configData.SPOPOCreateDateUpdateNote;
}
})
}
updateDate(res: any) {
console.log(res);
if (res && res.spoDate) {
if (this.orderData && this.orderData.OrderLine) {
let orderLineData = this.orderData.OrderLine.find((i) => i.OrderLineId === this.orderLineId);
let isAllOLSame = this.orderData.OrderLine.every((e) =>
e.OrderLinePromisingInfo && e.FulfillmentGroupId &&
e.FulfillmentGroupId === orderLineData.FulfillmentGroupId &&
e.OrderLinePromisingInfo.ShipFromLocationId === orderLineData.OrderLinePromisingInfo.ShipFromLocationId);
this.orderData.OrderLine.forEach((e) => {
if (this.orderLineId === e.OrderLineId) {
e.Extended.PODropDate = this.datePipe.transform(res.spoDate, 'MM/dd/yyy');
e.Extended.SPOPOCreateDateUpdated = true;
} else {
e.Extended.PODropDate = e.Extended.PODropDate;
e.Extended.SPOPOCreateDateUpdated = e.Extended.SPOPOCreateDateUpdated;
}
if (isAllOLSame) {
e.Extended.PODropDate = this.datePipe.transform(res.spoDate, 'MM/dd/yyy');
e.Extended.SPOPOCreateDateUpdated = true;
}
})
this.currentSpoDate = this.datePipe.transform(res.spoDate, 'MM/dd/yyy');
this.saveOrder(this.orderData)
}
}
// Extended.SPOPOCreateDateUpdated is flipped to true on updating
}
saveOrder(order: any) {
// let saveOrder: any;
// let postURL = environment.post_order_save;
// saveOrder = this.postService.postData(postURL, this.selectedOrganization, order);
this.postService.postData(environment.post_order_save, this.selectedOrganization, order)
.switchMap((res) => {
let data = {}
return this.postService.postData(environment.rhFetaFocURL, this.selectedOrganization, data)
})
.subscribe(response => {
},
error => { throw error; }
);
}
grantCheck() {
this.getService.getData(environment.getUserGrant + this.loggedInUser, this.selectedOrganization).subscribe(response => {
this.userGrantList = response;
let spoPoCreateDateGrant = this.userGrantList.some((res) => {
return res.ResourceId === "SPOPOCreateDateUpdate";
})
if (!spoPoCreateDateGrant) {
this.spoPoCreateDate = true;
} else {
this.spoPoCreateDate = false
}
console.log('SPOPOCREATEDATE', this.spoPoCreateDate);
});
}
}
can anyone suggest how to fix?

This is might solve your problem
<input type="date" value="2022-02-03" min="2022-02-03" max="2022-03-03">

Related

Pipe Translater in Html Element

So, dont know if anyone can help me. I have the below line of code in html :
<ion-item class="item-style">
<ion-label>{{ 'SettingsPage.ChangeLanguage' | translate }}</ion-label>
<ion-select [(ngModel)]="language" (ionChange)="onLanguageChange();" cancelText={{cancelText}} okText={{okText}}>
<ion-select-option value="en">{{ 'SettingsPage.English' | translate }}</ion-select-option>
<ion-select-option value="mt">{{ 'SettingsPage.Maltese' | translate }}</ion-select-option>
</ion-select>
</ion-item>
and the following methods in the .ts :
onLanguageChange() {
this.translate.use(this.language);
console.log(this.language);
this.globalVariableService.languageChanged = true;
this.globalVariableService.setCurrentLanguage(this.language);
this.storage.set('Language', this.language).then(() => {
this.sectorDataServiceProvider.populateSectorData().then(data => {
console.log('this.sectorInfo ', this.sectorDataServiceProvider.sectorInfo);
});
});
this.setOkAndCancelText();
}
setOkAndCancelText() {
if (this.language === 'en') {
this.cancelText = 'Cancel';
this.okText = 'OK';
} else if (this.language === 'mt') {
this.cancelText = 'Le';
this.okText = 'Iva';
}
}
I wish to remove the s setOkAndCancelText() which is being used to fill the cancelText={{cancelText}} parameter when the language changes within the app, and have something similar to:
<p [innerHTML]="'TermsOfUsePage.Header' | translate"></p>
Any ideas how i can make this possible please?
Instead of reliaing on libraries, you can create your custom service and add your local strings i.e key and value as following:
#Injectable({
providedIn: 'root'
})
export class LocalizationService {
localizedStrings: any;
constructor() {
this.localizedStrings = {
en: {
SettingsPage: {
cancelText: 'Cancel'
}
},
mt: {
SettingsPage: {
cancelText: 'Le'
}
}
}
}
getResource(keyString: string, workingLanguage: string): Promise<string> {
return new Promise((resolve, reject) => {
let resourceValue = null;
if(this.localizedStrings[workingLanguage].hasOwnProperty(keyString)) {
resourceValue = this.localizedStrings[workingLanguage][keyString];
} else {
resourceValue = this.getPropertyByKeyPath(this.localizedStrings[workingLanguage], keyString);
// if(!resourceValue) {
// debugger;
// }
}
if(resourceValue) {
resolve(resourceValue);
} else {
resolve(keyString);
}
});
}
private getPropertyByKeyPath(targetObj, keyPath) {
var keys = keyPath.split('.');
if(keys.length == 0) return undefined;
keys = keys.reverse();
var subObject = targetObj;
while(keys.length) {
var k = keys.pop();
if(!subObject.hasOwnProperty(k)) {
return undefined;
} else {
subObject = subObject[k];
}
}
return subObject;
}
}
Note that it is flexible, you can go deeper in objects. Now simply create a pipe for this service:
import { Pipe } from '#angular/core';
import { LocalizationService } from '../shared/localization.service';
#Pipe({
name:"translate"
})
export class LocalizedResourcePipe {
constructor(private localizationService: LocalizationService) {
}
transform(resourceKey: string, workingLanguage: string) {
return new Promise((resolve, reject) => {
if(!resourceKey) {
resolve();
} else {
this.localizationService.getResource(resourceKey, workingLanguage)
.then((value) => {
resolve(value);
});
}
});
}
}
Now simply call it in your HTML:
<ion-select [(ngModel)]="language" (ionChange)="onLanguageChange();" cancelText={{'SettingsPage.cancelText' | translate: 'en' | async}} okText={{'SettingsPage.cancelText' | translate: 'en' | async}}>
You can could make the the language parameter dynamic as well and in pipe, give it a default value. anyway here is the way to call it for your other language:
<ion-select [(ngModel)]="language" (ionChange)="onLanguageChange();" cancelText={{'SettingsPage.cancelText' | translate: 'mt' | async}} okText={{'SettingsPage.cancelText' | translate: 'mt' | async}}>
We have done it in following ways:
Installed the following packages:
"#ngx-translate/core": "11.0.1"
"#ngx-translate/http-loader": "4.0.0",
In app.module.js, add the following in imports:
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: AppHttpLoaderFactory,
deps: [HttpClient]
}
}),
export function AppHttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, Environment.frontend('/assets/i18n/'), '.json');
}
Here we have kept our en.json file under i18n folder where all key values of text are there.
After this you can use it in html template:
<ion-select [(ngModel)]="language" (ionChange)="onLanguageChange();" cancelText={{'cancel.text' | translate }} okText={{okText}/>
Here cancel.text is a key in en.json file.
Try this stackblitz example
Translate Service
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class TranslateService {
data: any = {};
constructor(private http: HttpClient) { }
use(lang: string): Promise<{}> {
return new Promise<{}>((resolve, reject) => {
const langPath = `assets/languageFiles/${lang || 'en'}.json`;
this.http.get<{}>(langPath).subscribe(
translation => {
this.data = Object.assign({}, translation || {});
resolve(this.data);
},
error => {
this.data = {};
resolve(this.data);
}
);
});
}
}
Translate Pipe
import { Pipe, PipeTransform } from '#angular/core';
import { TranslateService } from './translate.service';
#Pipe({
name: 'translate',
pure:false
})
export class TranslatePipe implements PipeTransform {
constructor(private translate: TranslateService) {}
transform(key: any): any {
return this.translate.data[key] || key;
}
}

How to use checkboxes to filter a simple table in angular 7

I am trying to use checkboxes to filter my table.
Its a normal table i do use bootstrap MDB tho.
I think I'm on the right path tho and i don't know what I'm doing wrong with the checkbox or the table :
This is my table :
<table mdbTable striped="true" [hidden]="!show" >
<thead>
<tr>
<th *ngFor="let head of tableColumn" scope="col">{{head}} </th>
</tr>
</thead>
<tbody>
<tr mdbTableCol *ngFor="let data of dataSourceFilterd | paginate: { id: 'listing_pagination', itemsPerPage: 10, currentPage: p, totalItems: totalPage }" >
<th scope="row">{{data.AITOR}}</th>
<td>{{data.SOG_MCOLH}}</td>
<td>{{data.GOBH_MCOLH}}</td>
<td>{{data.AORKH_MCOLH}}</td>
<td>{{data.MCOLH_N7}}</td>
<td>{{data.MCOLH_AAAA}}</td>
<td>{{data.TAOR_QTSR_EBRI}}</td>
<td>{{data.QOD_MCHSN}}</td>
<td>{{data.STTOS_RASHI_4_1}}</td>
<td>{{data.LQOCH_SHM_MQOTSR_EBRI}}</td>
<td>{{data.LQOCH_SHM_LOEZI_QTSR}}</td>
<td>{{data.LQOCH_QOD_LQOCH}}</td>
</tr>
</tbody>
</table>
This is the check box :
<input type="checkbox" [(ngModel)]="filter.OT" (ngModelChange)="filterChange()" />OT<br>
This is the Component :
import { Component, OnInit, ViewChild} from '#angular/core';
import { MarinServiceService } from 'src/app/services/marin-service.service';
#Component({
selector: 'app-containers-page',
templateUrl: './containers-page.component.html',
styleUrls: ['./containers-page.component.scss']
})
export class ContainersPageComponent implements OnInit {
tableColumn = ['AITOR', 'SOG_MCOLH', 'GOBH_MCOLH', 'AORKH_MCOLH', 'MCOLH_N7', 'MCOLH_AAAA', 'TAOR_QTSR_EBRI', 'QOD_MCHSN', 'STTOS_RASHI_4_1', 'LQOCH_SHM_MQOTSR_EBRI', 'LQOCH_SHM_LOEZI_QTSR', 'LQOCH_QOD_LQOCH'];
RG: any;
p: number = 1;
dataSource: any = [];
totalPage: number;
public show: boolean = false;
public tableHide: any = 'Show';
searchText: string = "";
total: any;
dataSourceFilterd: any = [];
filter = {
RG: true,
OT: true,
HC: true
};
constructor(private marinService: MarinServiceService) {}
ngOnInit() {
this.marinService.getAllContainers().subscribe((result) => {
this.dataSource = result;
this.total = this.dataSource.length;
this.dataSourceFilterd = this.dataSource;
})
}
toggle() {
this.show = !this.show;
if (this.show) {
this.tableHide = "Hide";
} else {
this.tableHide = "Show";
}
}
public doFilter = (value: string) => {
this.dataSource.filter = value.trim().toLocaleLowerCase();
}
public getRowsValue(flag) {
if (flag === null) {
return this.dataSource.length;
} else {
return this.dataSource.filter(i => (i.state == flag)).length;
}
}
filterChange() {
this.dataSourceFilterd = this.dataSource.filter(x =>
(x.category === 'RG' && this.filter.RG) ||
(x.category === 'OT' && this.filter.OT) ||
(x.category === 'HC' && this.filter.HC)
);
}
}
I have tried moving the checkbox into the table - Din't work.
I have tried changing the inputs for the checkbox - Didn't work.

Calendar don't show events in first load, only after trigger any element in window

Calendar don't show events in first load.
Only when I trigger any event like click in button to change the view from month to week for example.
I'm using Angular Calendar 6 + LINK
My project is made in Angular 6.
The calendar don't show data in first load, only after it when I trigger any event.
Everything is working as expected, so Ill give the Html (part of them) and the most important: the most important in this case.
HTML
...
<div [ngSwitch]="view">
<mwl-calendar-month-view *ngSwitchCase="CalendarView.Month" [viewDate]="viewDate" [events]="events"
[refresh]="refresh" [activeDayIsOpen]="activeDayIsOpen" (dayClicked)="dayClicked($event.day)"
(eventClicked)="handleEvent('Clicked', $event.event)" (eventTimesChanged)="eventTimesChanged($event)"
[locale]="locale" [weekStartsOn]="weekStartsOn" [weekendDays]="weekendDays" >
</mwl-calendar-month-view>
<mwl-calendar-week-view *ngSwitchCase="CalendarView.Week" [viewDate]="viewDate" [events]="events"
[refresh]="refresh" (eventClicked)="handleEvent('Clicked', $event.event)"
(eventTimesChanged)="eventTimesChanged($event)" [locale]="locale" [weekStartsOn]="weekStartsOn"
[weekendDays]="weekendDays" (beforeViewRender)="beforeMonthViewRender($event)">
</mwl-calendar-week-view>
<mwl-calendar-day-view *ngSwitchCase="CalendarView.Day" [viewDate]="viewDate" [events]="events"
[refresh]="refresh" (eventClicked)="handleEvent('Clicked', $event.event)"
(eventTimesChanged)="eventTimesChanged($event)" [locale]="locale" >
</mwl-calendar-day-view>
</div>
...
TYPESCRIPT
...
import {
Component,
ChangeDetectionStrategy,
ViewChild,
TemplateRef,
OnInit
} from "#angular/core";
import {
CalendarEvent,
CalendarView,
DAYS_OF_WEEK,
CalendarEventAction,
CalendarEventTimesChangedEvent,
CalendarDateFormatter
} from "angular-calendar";
import { NgbModal } from "#ng-bootstrap/ng-bootstrap";
import { Subject, Observable } from "rxjs";
import {
isSameDay,
isSameMonth} from "date-fns";
import { HomeService } from "../shared/service/home.service";
import { CalendarioEvento } from "../shared/model/calendario-eventos.model";
import { FormGroup, FormBuilder } from "#angular/forms";
import { CustomDateFormatter } from "../shared/service/custom-date-formatter.provide";
#Component({
selector: "mwl-demo-component",
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: "./home.component.html",
styleUrls: ["./home.component.css"],
providers: [
HomeService,
{
provide: CalendarDateFormatter,
useClass: CustomDateFormatter
}
]
})
export class HomeComponent implements OnInit {
#ViewChild("modalContent") modalContent: TemplateRef<any>;
activeDayIsOpen: boolean = true;
view: CalendarView = CalendarView.Month;
viewDate: Date = new Date();
locale: string = "pt-PT";
modalData: {
action: string;
event: CalendarEvent;
};
weekStartsOn: number = DAYS_OF_WEEK.MONDAY;
weekendDays: number[] = [DAYS_OF_WEEK.FRIDAY, DAYS_OF_WEEK.SATURDAY];
CalendarView = CalendarView;
listEvents: CalendarioEvento[] = [];
evento: CalendarioEvento;
eventsJson: string;
filtroForm: FormGroup;
botao: string;
acaoPermitida: boolean;
events: CalendarEvent[] = [];
events$: Observable<Array<CalendarEvent<{ event: any }>>>;
constructor(
private modal: NgbModal,
private homeService: HomeService ) {}
actions: CalendarEventAction[] = [
{
label: '<i class="fa fa-fw fa-pencil"></i>',
onClick: ({ event }: { event: CalendarEvent }): void => {
this.handleEvent("Edited", event);
}
},
{
label: '<i class="fa fa-fw fa-times"></i>',
onClick: ({ event }: { event: CalendarEvent }): void => {
this.events = this.events.filter(iEvent => iEvent !== event);
this.handleEvent("Deleted", event);
}
}
];
refresh: Subject<any> = new Subject();
ngOnInit() {
this.myMethodToInit();
}
myMethodToInit() {
this.homeService.getAll().subscribe(data => {
this.listEvents = data;
this.listEvents.forEach(element => {
var diaInicial = element.dataInicio.toString().substring(0, 2);
var diaFim = element.dataFim.toString().substring(0, 2);
var mesInicial = element.dataInicio.toString().substring(3, 5);
var mesFim = element.dataFim.toString().substring(3, 5);
var anoInicial = element.dataInicio.toString().substring(6, 10);
var anoFim = element.dataFim.toString().substring(6, 10);
var dataInicio = anoInicial + "-" + mesInicial + "-" + diaInicial;
var dataFim = anoFim + "-" + mesFim + "-" + diaFim;
let eve: CalendarEvent = {
title: element.descricao,
start: new Date(dataInicio),
id: element.id,
end: new Date(dataFim),
actions: this.actions
};
this.events.push(eve);
});
});
}
dayClicked({ date, events }: { date: Date; events: CalendarEvent[] }): void {
if (isSameMonth(date, this.viewDate)) {
this.viewDate = date;
if (
(isSameDay(this.viewDate, date) && this.activeDayIsOpen === true) ||
events.length === 0
) {
this.activeDayIsOpen = false;
} else {
this.activeDayIsOpen = true;
}
}
}
eventTimesChanged({
event,
newStart,
newEnd
}: CalendarEventTimesChangedEvent): void {
this.events = this.events.map(iEvent => {
if (iEvent === event) {
return {
...event,
start: newStart,
end: newEnd
};
}
return iEvent;
});
this.handleEvent("Dropped or resized", event);
}
handleEvent(action: string, event: CalendarEvent): void {
event.start = event.start;
this.modalData = { event, action };
this.modal.open(this.modalContent, { size: "lg" });
document
.getElementsByTagName("ngb-modal-window")
.item(0)
.setAttribute("id", "modal");
document.getElementById("modal").style.opacity = "1";
}
addEvent(action: string, event: CalendarEvent): void {
this.modalData = { event, action };
this.modal.open(this.modalContent, { size: "lg" });
document
.getElementsByTagName("ngb-modal-window")
.item(0)
.setAttribute("id", "modal");
document.getElementById("modal").style.opacity = "1";
}
deleteEvent(eventToDelete: CalendarEvent) {
this.events = this.events.filter(event => event !== eventToDelete);
}
setView(view: CalendarView) {
this.view = view;
}
closeOpenMonthViewDay() {
this.activeDayIsOpen = false;
}
resetar() {}
salvar() {
console.log("titulo:" + this.modalData.event.title);
console.log("start:" + this.modalData.event.start);
console.log("end:" + this.modalData.event.end);
}
}
...
FIRST LOAD:
AFTER ANY EVENT (for example, click in week view and return to month view):
Problem solved after some hours rs.
Only 2 adjusts in component.ts and it works!
1º Include: encapsulation: ViewEncapsulation.None
2º Inside ngOnInit, after retrieve all events refresh the calendar with the command: this.refresh.next();
Code:
ViewEncapsulation.None
...
selector: "calendario-ico",
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: "./calendario.component.html",
styleUrls: ["./calendario.component.css"],
encapsulation: ViewEncapsulation.None,
providers: [
...
this.refresh.next();
ngOnInit() {
this.AtivarFormulario();
this.homeService.getAll("", "", "").subscribe(data => {
this.listEvents = data;
this.listEvents.forEach(element => {
var diaInicial = element.dataInicio.toString().substring(0, 2);
var diaFim = element.dataFim.toString().substring(0, 2);
var mesInicial = element.dataInicio.toString().substring(3, 5);
var mesFim = element.dataFim.toString().substring(3, 5);
var anoInicial = element.dataInicio.toString().substring(6, 10);
var anoFim = element.dataFim.toString().substring(6, 10);
var dataInicio = anoInicial + "-" + mesInicial + "-" + diaInicial;
var dataFim = anoFim + "-" + mesFim + "-" + diaFim;
let eve: CalendarEvent = {
title: element.descricao,
start: new Date(dataInicio),
id: element.id,
end: new Date(dataFim),
actions: this.actions
};
this.events.push(eve);
});
this.refresh.next();
});
}
Hi my suggestion is remove ngOnInit, it will load first time.

IE Datepicker too long

I have a date picker that is to be IE friendly. However when I use it, it's displaying far too long.
HTML:
<label class="mr-sm-2" for="startDate">Start Date:</label>
<date-picker
class="mr-sm-2"
name="startDate"
formControlName="startDate">
</date-picker>
datepicker.component.ts:
import * as _ from "lodash" ;
import * as moment from 'moment';
import { Component, Input, forwardRef, ViewEncapsulation } from '#angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '#angular/forms';
#Component({
selector: 'date-picker',
template: `
<ng-container *ngIf="isGoodBrowser; else datePickerFallback">
<input
type="date"
class="form-control text-right"
[class.is-invalid]="invalid"
[(ngModel)]="value"
[disabled]="disabled"
/>
</ng-container>
<ng-template #datePickerFallback>
<div class="fallback-date-picker" [class.invalid]="invalid">
<my-date-picker
[options]="options"
[disabled]="disabled"
[(ngModel)]="value"
(dateChanged)="value = $event">
</my-date-picker>
</div>
</ng-template>
`,
encapsulation: ViewEncapsulation.None,
styles: [
`.fallback-date-picker.invalid .mydp {
border-color: #dc3545;
}`,
`.fallback-date-picker .mydp .selection {
text-align: right;
padding-right: 65px;
}`
],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => DatePickerComponent),
multi: true
}
]
})
export class DatePickerComponent implements ControlValueAccessor {
private _value: any = null;
private propagateChange = _.identity;
isGoodBrowser: boolean = true;
disabled: boolean = false;
options: any = {
dateFormat: 'dd/mm/yyyy',
editableDateField: false
};
constructor() {
const userAgent = window.navigator.userAgent;
if (userAgent.indexOf('MSIE') >= 0) this.isGoodBrowser = false;
if (userAgent.indexOf('Trident') >= 0) this.isGoodBrowser = false;
if (userAgent.indexOf('Edge') >= 0) this.isGoodBrowser = true;
}
#Input() invalid: boolean = false;
#Input()
set value(v: any) {
if (v) {
if (_.isString(v)) {
const mDate = moment(v);
if (this.isGoodBrowser) {
this._value = v;
} else {
this._value = {
date: {
year: mDate.year(),
month: mDate.month() + 1,
day: mDate.date()
}
};
}
this.propagateChange(v);
} else if (v && v.jsdate) {
const mDate = moment(v.jsdate);
this.propagateChange(mDate.format('YYYY-MM-DD'));
} else {
this.propagateChange(null);
}
} else {
this._value = null;
this.propagateChange(null);
}
}
get value() {
return this._value;
}
writeValue(value: any) {
this.value = value ? value : null;
}
registerOnChange(fn: any) {
this.propagateChange = fn;
}
registerOnTouched() { }
setDisabledState(isDisabled: boolean) {
this.disabled = isDisabled;
}
}
The images shows how the date picker displays, it goes across off the screen.
I feel like the problem might be in the html layout as this doesn't happen everytime I use the date picker.
I have solved the issue and it has nothing to do with the code shown.

How to set default format as ('dd/mm/yyyy') in ng-bootstrap

https://puu.sh/yThgV/bd55df9829.png
html
<label for="date">{{ "date" | translate }}</label>
<input type="date" class="form-control checking-field" id="date">
I want to get that format ('dd/mm/yyyy'). Any Suggestion?
extends my comment
In your app.module
import { NgbDatepickerConfig, NgbDateParserFormatter } from '#ng-bootstrap/ng-bootstrap';
import { NgbDateFRParserFormatter } from "./ngb-date-fr-parser-formatter"
#Component({
providers: [{provide: NgbDateParserFormatter, useClass: NgbDateFRParserFormatter}]
})
export class AppComponent {}
In your NgbDateFRParserFormater
//your NgbDateFRParserFormater extends from NgbDateParserFormatter
//Is a Injectable that have two functions
#Injectable()
export class NgbDateFRParserFormatter extends NgbDateParserFormatter {
parse(value: string): NgbDateStruct { //parse receive your string dd/mm/yyy
//return a NgbDateStruct
//calculate year,month and day from "value"
return {year:year,month:month,day:day}
}
format(date: NgbDateStruct): string { //receive a NgbDateStruct
//return a string
return ''+date.day+'/'+date.month+'/'+date.year;
}
}
My complete working solution:
Create a folder named "date-picker" and add the following files inside it.
date-picker > ngb-date-parser-formatter-ext.service.ts
date-picker > index.ts
The file
date-picker > ngb-date-parser-formatter-ext.service.ts
import { NgbDateParserFormatter, NgbDateStruct } from "#ng-bootstrap/ng-bootstrap";
import { Injectable } from "#angular/core";
#Injectable()
export class NgbDateParserFormatterExtService extends NgbDateParserFormatter {
private dateSeparatorChar: string = "-";
// dateFormat should be "yyyy-MM-dd" or "dd-MM-yyyy" with the valid separator.
private dateFormat = `yyyy${this.dateSeparatorChar}MM${this.dateSeparatorChar}dd`;
parse(value: string): NgbDateStruct {
if (value === "") {
return null;
}
const dateString: string = value;
const dateValues = dateString.split(this.dateSeparatorChar);
if (dateValues.length !== 3) {
return null;
}
let dayIndex: number;
let yearIndex: number;
if (this.dateFormat === "dd-MM-yyyy") {
dayIndex = 0;
yearIndex = 2;
} else {
dayIndex = 2;
yearIndex = 0;
}
const year = Number(dateValues[yearIndex]);
const month = Number(dateValues[1]);
const day = Number(dateValues[dayIndex]);
const date: NgbDateStruct = {
year: year, month: month, day: day
};
return date;
}
format(date: NgbDateStruct): string {
if (date === null) {
return "";
}
const dayString: string = date.day < 10 ? `0${date.day}` : `${date.day}`;
const monthString: string = date.month < 10 ? `0${date.month}` : `${date.month}`;
const separator = this.dateSeparatorChar;
const dateString = this.dateFormat === "dd-MM-yyyy"
? `${dayString}${separator}${monthString}${separator}${date.year}`
: `${date.year}${separator}${monthString}${separator}${dayString}`;
return dateString;
}
}
The file
date-picker > index.ts
import { NgbDateParserFormatter } from "#ng-bootstrap/ng-bootstrap";
import { NgbDateParserFormatterExtService } from "./ngb-date-parser-formatter-ext.service";
export const NgbDateParserFormatterExtProvider =
{ provide: NgbDateParserFormatter, useClass: NgbDateParserFormatterExtService };
In the file
app.module.ts
import { NgbDateParserFormatterExtProvider } from "./common/services/date-picker";
#NgModule({
providers: [...., NgbDateParserFormatterExtProvider],
})
export class AppModule { }
In your
your-component1.component.html
<div class="form-group">
<label>Publish Date</label><span> * </span>
<input #datepicker="ngbDatepicker" class="form-control" name="datepicker" formControlName="publishDate"
ngbDatepicker (click)="datepicker.toggle()" placeholder="yyyy-MM-dd" />
</div>
I'm using Reactive forms.
You can change the date format to "dd-MM-yyyy" or "dd/MM/yyyy" by setting the variable
private dateFormat = `yyyy${this.dateSeparatorChar}MM${this.dateSeparatorChar}dd`;
Regards..
In general you need to use directive.
So, you can use one of ready-made date-time pickers for angular. Like this: https://www.npmjs.com/package/angular-date-time-input
Or create your own directive to make it work.
myModule.directive(
'dateInput',
function(dateFilter) {
return {
require: 'ngModel',
template: '<input type="date"></input>',
replace: true,
link: function(scope, elm, attrs, ngModelCtrl) {
ngModelCtrl.$formatters.unshift(function (modelValue) {
return dateFilter(modelValue, 'yyyy-MM-dd');
});
ngModelCtrl.$parsers.unshift(function(viewValue) {
return new Date(viewValue);
});
},
};
});
I took this code from: https://stackoverflow.com/a/18062552/3710672