I would like to remove the value 0 in the field Fiscal Year
illustration
search-dta.ts
export class SearchDta {
registreNational: number;
fiscalYear: number;
country: number;
constructor(
registreNational: number = 0,
fiscalYear: number = 0,
country: number = 0,
) {
this.registreNational = registreNational;
this.fiscalYear = fiscalYear;
this.country = country
}
}
search-dta.component.html
<div class="row row-cols-3 pt-3">
<div class="col text-end">
<label for="fiscalYear" class="form-label">Fiscal Year</label>
</div>
<div class="col-4">
<input id="fiscalYear" name="fiscalYear" type="text" class="form-control" name="fiscalYear"
style="min-width: 380px" [(ngModel)]="search.fiscalYear" maxlength="10">
</div>
</div>
search-dta.component.ts
export class SearchDtaComponent implements OnDestroy {
private unsubscribe$ = new Subject < void > ();
#Input() mode: string = "";
#Input() title: string = "";
#Input() canSelectAllTitles: boolean = false;
#Input() showWarnings: boolean = false;
#Input() disabledSvm: number[] = [];
#Input() saveState: Observable < string > = new Observable < string > ();
#Input() url: string = '';
#Input() from ? : string;
isModal: boolean = false;
markets$ = this.service.markets$;
search: SearchDta = new SearchDta();
data ? : SearchDtaResponse;
countries: Country[] = [];
#Output() selectedPersonnePhysiqueDta = new EventEmitter < PersonnePhysiqueDta | undefined > ();
#Output() changedState = new EventEmitter < SearchDta > ();
constructor(private service: SearchDtaService, private modalService: BsModalService, private router: Router) {}
ngOnInit() {
this.saveState.subscribe((url) => localStorage.setItem(url + '.search', JSON.stringify(this.search)));
const search = localStorage.getItem(this.url + '.search');
if (search) {
this.search = JSON.parse(search);
localStorage.removeItem(this.url + '.search')
}
this.service.getPaysDta().pipe(
takeUntil(this.unsubscribe$)
).subscribe((countries) => this.countries = countries);
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
submit(): void {
if (!this.isModal) {
const modalRef = this.modalService.show(SearchDtaResultModalComponent, {
...SEARCH_TITLE_MODAL_OPTIONS,
initialState: {
title: this.title,
isLoading: true,
disabledSvm: this.disabledSvm,
showWarnings: this.showWarnings
}
});
modalRef.content!.selectedPersonnePhysiqueDta.pipe(
takeUntil(this.unsubscribe$)
).subscribe((val: PersonnePhysiqueDta | undefined) => {
this.selectPersonnePhysiqueDta(val);
if (this.mode === 'create') {
this.router.navigate([
"/dta/create/" +
val?.NUMEROREGISTRENATIONAL +
"/" +
this.search.country +
"/" +
this.search.fiscalYear
]);
} else if (this.mode === 'delete') {
this.router.navigate([
"/dta/delete/" +
val?.NUMEROREGISTRENATIONAL +
"/" +
this.search.country +
"/" +
this.search.fiscalYear
]);
} else {
this.router.navigate([
"/dta/follow-up/" +
val?.NUMEROREGISTRENATIONAL +
"/" +
this.search.country +
"/" +
this.search.fiscalYear
]);
}
modalRef?.hide();
});
this.searchDta(true).pipe(
takeUntil(modalRef.content!.selectedPersonnePhysiqueDta)
).subscribe(res => {
if (modalRef) {
modalRef.content!.isLoading = false;
modalRef.content!.personnePhysique = res.DTA.PP;
if (!res.DTA.PP) {
modalRef.hide();
}
}
});
} else {
this.searchDta(false).pipe(
takeUntil(this.unsubscribe$)
).subscribe(res => {
this.data = res;
});
}
}
private searchDta(hideLoading: boolean): Observable < SearchDtaResponse > {
return this.service.searchDta(this.search, hideLoading).pipe(
takeUntil(this.unsubscribe$)
);
}
selectPersonnePhysiqueDta(personnePhysiqueDta: PersonnePhysiqueDta | undefined = undefined): void {
this.selectedPersonnePhysiqueDta.emit(personnePhysiqueDta);
}
changeState(): void {
this.changedState.emit(this.search);
}
}
How can I remove the 0?
Thank you very much
Try this:
in .ts
registreNational:number|undefined;
fiscalYear number|undefined ;
country: number |undefined
;
and add in html
<div class="col-4" *ngIf="search.fiscalYear>
<input id="fiscalYear" name="fiscalYear" type="text" class="form-control" name="fiscalYear" style="min-width: 380px" [(ngModel)]="search.fiscalYear" maxlength="10">
</div>
you're setting fiscalYear to 0 and binding that value to the input. you need to not set it to 0 if you don't want it to show 0
export class SearchDta {
constructor(
public registreNational: number = 0,
public fiscalYear: number | null = null,
public country: number = 0,
) {
}
}
Related
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">
I'm creating a scheduler in which I can add tasks I've done in a certain amount of time. The tasks get added in a to-do list-like manner.
I'm trying to remove individual items from a list both from the front-end and from LocalStorage but I haven't found a solution that works yet. The function I'm trying to make work is "RemoveTask()".
Here's my code:
HTML:
<div class="modalbox" [class.active]="modalboxActive">
<div class="modal">
<p>What did you do?</p>
<input type="text" [(ngModel)]="activity.name" maxlength="22" />
<button (click)="addTask()" [disabled]="activity.name === ''">OK</button>
</div>
</div>
<div class="boxSuper">
<div class="boxLeft">
<div class="containerUp">
<button id="start" (click)="startTimer()">START</button>
<button id="pause" (click)="pauseTimer()">PAUSE</button>
<button id="stop" (click)="stopTimer()">STOP</button>
<button (click)="removeAll()">REMOVE ALL</button>
</div>
<div class="containerDown">
<p>{{ display }}</p>
</div>
</div>
<div class="boxRight">
<div class="containerLeft">
<ul class="listElementLeft" *ngFor="let item of tasks">
<div class="card">
<ul class="order">
<li class="list-group-item"><span>START:</span>{{ item.start }}</li>
<li class="list-group-item"><span>END:</span>{{ item.end }}</li>
<li class="list-group-item">
<span>LENGTH:</span>{{ item.length }}
</li>
</ul>
<div class="subcard">
<li>
{{ item.name }}
</li>
</div>
<div class="buttonCard">
<button (click)="removeTask(item.id)">REMOVE</button>
</div>
</div>
</ul>
</div>
</div>
</div>
TS:
import { importExpr } from '#angular/compiler/src/output/output_ast';
import { Component, OnInit } from '#angular/core';
import { timer } from 'rxjs';
import { Activity } from '../activity';
import { Result } from '../result';
#Component({
selector: 'app-timer',
templateUrl: './timer.component.html',
styleUrls: ['./timer.component.scss'],
})
export class TimerComponent implements OnInit {
ngOnInit() {
this.tasks = JSON.parse(localStorage.getItem('token') ?? '');
}
time: number = 0;
display: string | undefined;
interval: any;
modalboxActive = false;
startTime: string | undefined;
endTime: string | undefined;
id: number | undefined;
activity: Activity = {
name: '',
};
tasks: Result[] = [];
startFunc() {
this.startTime = new Date().toString().split(' ')[4];
}
endFunc() {
this.endTime = new Date().toString().split(' ')[4];
}
//task actions
addTask() {
var el: Result = {
id: this.id!,
name: this.activity.name,
end: this.endTime,
start: this.startTime,
length: this.display,
};
this.tasks.push(el);
localStorage.setItem('token', JSON.stringify(this.tasks));
this.activity.name = '';
this.modalboxActive = false;
this.resetTimer();
}
removeAll() {
localStorage.clear();
}
removeTask(id: number) {
// this.tasks.splice(id, 1);
this.tasks = this.tasks.filter((item) => item.id !== id);
}
//timer actions
startTimer() {
console.log('go');
this.interval = setInterval(() => {
if (this.time === 0) {
this.time++;
} else {
this.time++;
}
this.display = this.transform(this.time);
}, 1000);
this.startFunc();
}
transform(value: number): string {
var sec_num = value;
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - hours * 3600) / 60);
var seconds = sec_num - hours * 3600 - minutes * 60;
return hours + ':' + minutes + ':' + seconds;
}
pauseTimer() {
clearInterval(this.interval);
}
stopTimer() {
console.log('show');
this.modalboxActive = true;
clearInterval(this.interval);
this.endFunc();
}
resetTimer() {
console.log('reset');
this.time = 0;
}
}
Result interface:
export interface Result {
id: number;
start: string | undefined;
end: string | undefined;
length: string | undefined;
name: string | undefined;
}
It looks like when you add an item in task list, the task.id is always undefined. You need to give it an unique id in order to identify it on removal.
Try to change the following code:
from:
ngOnInit() {
this.tasks = JSON.parse(localStorage.getItem('token') ?? '');
}
// task actions
addTask() {
var el: Result = {
id: this.id!, // always is undefined
name: this.activity.name,
end: this.endTime,
start: this.startTime,
length: this.display,
};
this.tasks.push(el);
localStorage.setItem('token', JSON.stringify(this.tasks));
this.activity.name = '';
this.modalboxActive = false;
this.resetTimer();
}
removeAll() {
localStorage.clear();
}
removeTask(id: number) {
// this.tasks.splice(id, 1);
this.tasks = this.tasks.filter((item) => item.id !== id);
}
to:
ngOnInit() {
this.tasks = JSON.parse(localStorage.getItem('token')) ?? [];
}
// task actions
addTask() {
var el: Result = {
id: this.tasks.length + 1,
name: this.activity.name,
end: this.endTime,
start: this.startTime,
length: this.display,
};
this.tasks.push(el);
localStorage.setItem('token', JSON.stringify(this.tasks));
this.activity.name = '';
this.modalboxActive = false;
this.resetTimer();
}
removeAll() {
this.tasks = [];
localStorage.removeItem('token');
}
removeTask(id: number) {
this.tasks = this.tasks.filter((item) => item.id !== id);
localStorage.setItem('token', JSON.stringify(this.tasks)); // also, update localStorage
}
You can check a working example here.
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.
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 get data from json rather from table-data.ts
iam confused.tried my best cant able to find the solution.where should i do alteration i think from private data:array=TableData;
It will be helpful if anyone give a solution.
Demo.component.ts
export class TableDemoComponent implements OnInit { public rows:Array<any> = [];
public columns:Array<any> = [
{title: 'Company', name: 'name', filtering: {filterString: '', placeholder: 'Filter by name'}},
{
title: 'Position',
name: 'position',
sort: false,
filtering: {filterString: '', placeholder: 'Filter by position'}
},
{title: 'Location', name: 'office', sort: '', filtering: {filterString: '', placeholder: 'Filter by Location'}},
{title: 'Date', className: 'text-warning', name: 'startDate'},];
public page:number = 1;
public itemsPerPage:number = 10;
public maxSize:number = 5;
public numPages:number = 1;
public length:number = 0;
public config:any = {
paging: true,
sorting: {columns: this.columns},
filtering: {filterString: ''},
className: ['table-striped', 'table-bordered']
};
private data:Array<any> = TableData;
public constructor() {
this.length = this.data.length;
}
public ngOnInit():void {
this.onChangeTable(this.config);
}
public changePage(page:any, data:Array<any> = this.data):Array<any> {
let start = (page.page - 1) * page.itemsPerPage;
let end = page.itemsPerPage > -1 (startpage.itemsPerPage):data.length;
return data.slice(start, end);
}
public changeSort(data:any, config:any):any {
if (!config.sorting) {
return data;
}
let columns = this.config.sorting.columns || [];
let columnName:string = void 0;
let sort:string = void 0;
for (let i = 0; i < columns.length; i++) { if(columns[i].sort!==''&&columns[i].sort!==false{columnNamecolumns[i].name;
sort = columns[i].sort;
}
}
if (!columnName) {
return data;
}
// simple sorting
return data.sort((previous:any, current:any) => {
if (previous[columnName] > current[columnName]) {
return sort === 'desc' ? -1 : 1;
} else if (previous[columnName] < current[columnName]) {
return sort === 'asc' ? -1 : 1;
}
return 0;
});
}
public changeFilter(data:any, config:any):any {
let filteredData:Array<any> = data;
this.columns.forEach((column:any) => {
if (column.filtering) {
filteredData = filteredData.filter((item:any) => {
return item[column.name].match(column.filtering.filterString); });
}
});
if (!config.filtering) {
return filteredData;
}
if (config.filtering.columnName) {
return filteredData.filter((item:any) => item[config.filtering.columnName].match(this.config.filtering.filterString));
}
let tempArray:Array<any> = [];
filteredData.forEach((item:any) => {
let flag = false;
this.columns.forEach((column:any) => {
if (item[column.name].toString().match(this.config.filtering.filterString)) {
flag = true;
}
});
if (flag) {
tempArray.push(item);
}
});
filteredData = tempArray;
return filteredData;
}
public onChangeTable(config:any, page:any = {page: this.page,itemsPerPage: this.itemsPerPage}):any {
if (config.filtering) {
Object.assign(this.config.filtering, config.filtering);
}
if (config.sorting) {
Object.assign(this.config.sorting, config.sorting);
}
let filteredData = this.changeFilter(this.data, this.config);
let sortedData = this.changeSort(filteredData, this.config);
this.rows = page && config.paging ? this.changePage(page,sortedData):sortedData;
this.length = sortedData.length;
}
public onCellClick(data: any): any {
console.log(data);
}}
Datatable.ts
export const TableData:Array<any> = [
{
'name': 'Victoria Cantrell',
'position': 'Integer Corporation',
'office': 'Croatia',
'ext': `<strong>0839</strong>`,
'startDate': '2015/08/19',
'salary': 208.178
}, {
'name': 'Pearl Crosby',
'position': 'In PC',
'office': 'Cambodia',
'ext': `<strong>8262</strong>`,
'startDate': '2014/10/08',
'salary': 114.367
}, {
'name': 'Colette Foley',
'position': 'Lorem Inc.',
'office': 'Korea, North',
'ext': '8968',
'startDate': '2015/07/19',
'salary': 721.473
}
];
Table-demo.html
<div class="row">
<div class="col-md-4">
<input *ngIf="config.filtering" placeholder="Filter allcolumns"
[ngTableFiltering]="config.filtering"
class="form-control"
(tableChanged)="onChangeTable(config)"/>
</div>
</div>
<br>
<ng-table [config]="config"
(tableChanged)="onChangeTable(config)"
(cellClicked)="onCellClick($event)"
[rows]="rows" [columns]="columns">
</ng-table>
<pagination *ngIf="config.paging"
class="pagination-sm"
[(ngModel)]="page"
[totalItems]="length"
[itemsPerPage]="itemsPerPage"
[maxSize]="maxSize"
[boundaryLinks]="true"
[rotate]="false"
(pageChanged)="onChangeTable(config, $event)"
(numPages)="numPages = $event">
</pagination>
If you wanted to use the TableData in a different file you would have to import it. I have added an example at the top that show you how to import it. All you do is just create another file and import what you need. I tidied up your code and fixed some syntax errors and put some notes next to bits where stuff was undefined which would throw errors also put some explanations next to the top in how to import things:
import {OnInit} from "#angular/core"
import {TableData} from "./test2" //test2 is the name of the file
// ./ current directory
// ../../ up two directories
export class TableDemoComponent implements OnInit {
public rows: Array<any> = [];
public columns: Array<any> =
[
{
title: 'Company',
name: 'name',
filtering: {
filterString: '', placeholder: 'Filter by name'
}
},
{
title: 'Position',
name: 'position',
sort: false,
filtering: {
filterString: '', placeholder: 'Filter by position'
}
},
{
title: 'Location',
name: 'office',
sort: '',
filtering: {
filterString: '', placeholder: 'Filter by Location'
}
},
{
title: 'Date',
className: 'text-warning',
name: 'startDate'
}
];
public page: number = 1;
public itemsPerPage: number = 10;
public maxSize: number = 5;
public numPages: number = 1;
public length: number = 0;
public config: any = {
paging: true,
sorting: {columns: this.columns},
filtering: {filterString: ''},
className: ['table-striped', 'table-bordered']
};
private data: Array<any> = TableData;
public constructor() {
this.length = this.data.length;
}
public ngOnInit(): void {
this.onChangeTable(this.config);
}
public changePage(page: any, data: Array<any> = this.data): Array<any> {
let start = (page.page - 1) * page.itemsPerPage;
//startpage is not defined
let end = page.itemsPerPage > -1 ? startpage.itemsPerPage : data.length;
return data.slice(start, end);
}
public changeSort(data: any, config: any): any {
if (!config.sorting) {
return data;
}
let columns = this.config.sorting.columns || [];
let columnName: string = void 0;
let sort: string = void 0;
for (let i = 0; i < columns.length; i++) {
if (columns[i].sort !== '' && columns[i].sort !== false) {
//columnNamecolumns is not defined
columnNamecolumns[i].name;
sort = columns[i].sort;
}
}
if (!columnName) {
return data;
}
// simple sorting
return data.sort((previous: any, current: any) => {
if (previous[columnName] > current[columnName]) {
return sort === 'desc' ? -1 : 1;
} else if (previous[columnName] < current[columnName]) {
return sort === 'asc' ? -1 : 1;
}
return 0;
});
}
public changeFilter(data: any, config: any): any {
let filteredData: Array<any> = data;
this.columns.forEach((column: any) => {
if (column.filtering) {
filteredData = filteredData.filter((item: any) => {
return item[column.name].match(column.filtering.filterString);
});
}
});
if (!config.filtering) {
return filteredData;
}
if (config.filtering.columnName) {
return filteredData.filter((item: any) => item[config.filtering.columnName].match(this.config.filtering.filterString));
}
let tempArray: Array<any> = [];
filteredData.forEach((item: any) => {
let flag = false;
this.columns.forEach((column: any) => {
if (item[column.name].toString().match(this.config.filtering.filterString)) {
flag = true;
}
});
if (flag) {
tempArray.push(item);
}
});
filteredData = tempArray;
return filteredData;
}
public onChangeTable(config: any, page: any = {page: this.page, itemsPerPage: this.itemsPerPage}): any {
if (config.filtering) {
Object.assign(this.config.filtering, config.filtering);
}
if (config.sorting) {
Object.assign(this.config.sorting, config.sorting);
}
let filteredData = this.changeFilter(this.data, this.config);
let sortedData = this.changeSort(filteredData, this.config);
this.rows = page && config.paging ? this.changePage(page, sortedData) : sortedData;
this.length = sortedData.length;
}
public onCellClick(data: any): any {
console.log(data);
}
}
I hope this is what you meant for. I am reading my data from external source (not json - but I think this is the same) by this way:
public constructor(private dataService: DataService ){
this.dataService.getUsers().then(users => {this.data = users; this.length = this.data.length;}).
catch(error => this.error = error);
}
public ngOnInit():void {
this.dataService.getUsers().then(users => {this.data = users; this.onChangeTable(this.config);}).
catch(error => this.error = error);
}
in this example my data is users. I am calling it from my data service. I hope it helps.