How to reset primeng datepick calender - angular7

I am trying to reset primeng datepick calender but not working.I am working in angular 8.I have created custom datepicker component using primeng.I have given my code below.How to reset that?Anyone can have idea?please help to find the solution.
app.component.html:
<p-calendar dateformat="mm/dd/yyyy" [numberofmonths]="4" selectionmode="range" formControlName="datePick"></p-calendar>
<button (click)="resetdate()">Reset Date</button>
app.component.ts:
#ViewChild('p-calendar') calendar: any;
resetdate(){
this.calendar.value = null;
}

You are using reactive forms, in the reactive form it will set with form control setValue method.
Update: You can provide model value as an array.
component.html
<hello name="{{ name }}"></hello>
<div [formGroup]="myGroup">
<p>
Date Reset
</p>
<p-calendar formControlName="date" selectionMode="range" [readonlyInput]="true"></p-calendar>
<button (click)="reset()">Reset</button>
<button (click)="setCustomDateRange()">Set Custom Date Range</button>
</div>
component.ts
import { Component } from '#angular/core';
import { FormControl , FormGroup} from '#angular/forms';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
yearRange = '2000:2020';
myGroup: any;
rangeDates: Date[];
constructor(){
this.myGroup = new FormGroup({
date: new FormControl('')
});
}
setCustomDateRange(){
var date = new Date();
date.setDate(date.getDate() + 10);
this.myGroup.get('date').setValue([new Date(), date]);
}
reset(){
console.log(this.myGroup.get('date').value)
this.myGroup.get('date').setValue(null);
}
}
check working code

Use [(ngModel)] as below:
<p-calendar [(ngModel)]="value"></p-calendar>
and in ts use:
value: Date;
resetdate() {
this.value = null;
}
See working code

If necessary, like for me, you can destroy and recreate the component like this :
<p-calendar *ngIf="showCalendar"></p-calendar>
<button (click)="resetdate()">Reset Date</button>
detectChanges() method apply *ngIf and destroy the component:
constructor(private changeDetectorRef: ChangeDetectorRef) { }
showCalendar = true;
resetdate(): void {
this.showCalendar = false;
this.changeDetectorRef.detectChanges();
this.showCalendar = true;
}

no need to create separate method to reset data binding on module. just use property showClear="true" on tag
<p-calendar [(ngModel)]="value" [showClear]="true"></p-calendar>
for reference check documentation

Related

How to set values for date range in primeng

I am trying to set value during initializing form using primeng datepick calender but not working.I am working in angular 8.I have created custom datepicker component using primeng.I have given my code below.How to set date range value that?Anyone can have idea?please help to find the solution.
app.component.html:
<p-calendar
[(ngModel)]="datesRangeFilter"
selectionMode="range" view="month" dateFormat="mm/yy" [readonlyInput]="true"
[showIcon]="true">
</p-calendar>
app.component.ts:
datesRangeFilter:Date;
ngOnInit(){
let yesterday = ( d => new Date(d.setDate(d.getDate()-1)) )(new Date);
this.datesRangeFilter=yesterday +'-'+new Date;
}
You can assign two different dates as an array, and it will be bind to the model.
component.html
<hello name="{{ name }}"></hello>
<div [formGroup]="myGroup">
<p>
Date Reset
</p>
<p-calendar formControlName="date" selectionMode="range" [readonlyInput]="true"></p-calendar>
<button (click)="reset()">Reset</button>
<button (click)="setCustomDateRange()">Set Custom Date Range</button>
</div>
Component.ts
import { Component } from '#angular/core';
import { FormControl , FormGroup} from '#angular/forms';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
yearRange = '2000:2020';
myGroup: any;
rangeDates: Date[];
constructor(){
this.myGroup = new FormGroup({
date: new FormControl('')
});
}
setCustomDateRange(){
var date = new Date();
date.setDate(date.getDate() + 10);
this.myGroup.get('date').setValue([new Date(), date]);
}
reset(){
console.log(this.myGroup.get('date').value)
this.myGroup.get('date').setValue(null);
}
}
[Working code][1]

Conditionally change date format of owl-date-time picker in angular

I using owlDateTime(https://daniel-projects.firebaseapp.com/owlng/date-time-picker) picker in may project.
After date selected it shows the mm/dd/yyyy format but I want to change this format to dd/mm/yyyy conditionally.
bellow are my code
.component.html
<input [max]="max" [owlDateTimeTrigger]="dt_date_time" [owlDateTime]="dt_date_time" formControlName="date_time" id="date_time" type="text" class="form-control date-picker date-field hasDatepicker" placeholder="dd/mm/yyyy" name="date_time" value="">
<owl-date-time [pickerType]="'calendar'" #dt_date_time></owl-date-time>
I have solve above problem using following code
import { Component, OnInit } from '#angular/core';
import { DateTimeAdapter } from 'ng-pick-datetime';
#Component({
selector: 'app-home-layout',
templateUrl: './home-layout.component.html',
styleUrls: ['./home-layout.component.css']
})
export class HomeLayoutComponent implements OnInit {
constructor(dateTimeAdapter: DateTimeAdapter<any>) {
let UserAttributes=JSON.parse(localStorage.getItem('UserAttributes'));
let country= UserAttributes['custom:country'];
if(country=='USA'){
dateTimeAdapter.setLocale('us');
}else{
dateTimeAdapter.setLocale('en-IN');
}
}
ngOnInit() {
}
}

Placeholder in input text with some default tags in angular 6

Please refer the above image. I want to add Add a tag placeholder front of some default tags. Please refer below link. https://material.angular.io/components/chips/overview
I have added code here. I am using angular 6.
html code:
<mat-form-field class="example-chip-list">
<mat-chip-list #chipList>
<mat-chip *ngFor="let fruit of fruits" [selectable]="selectable"
[removable]="removable" (removed)="remove(fruit)">
{{fruit.name}}
<mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
</mat-chip>
<input placeholder="New fruit..."
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event)">
</mat-chip-list>
</mat-form-field>
typescript code:
import {COMMA, ENTER} from '#angular/cdk/keycodes';
import {Component} from '#angular/core';
import {MatChipInputEvent} from '#angular/material';
export interface Fruit {
name: string;
}
#Component({
selector: 'chips-input-example',
templateUrl: 'chips-input-example.html',
styleUrls: ['chips-input-example.css'],
})
export class ChipsInputExample {
visible = true;
selectable = true;
removable = true;
addOnBlur = true;
readonly separatorKeysCodes: number[] = [ENTER, COMMA];
fruits: Fruit[] = [
{name: 'Lemon'},
{name: 'Lime'},
{name: 'Apple'},
];
add(event: MatChipInputEvent): void {
const input = event.input;
const value = event.value;
if ((value || '').trim()) {
this.fruits.push({name: value.trim()});
}
if (input) {
input.value = '';
}
}
remove(fruit: Fruit): void {
const index = this.fruits.indexOf(fruit);
if (index >= 0) {
this.fruits.splice(index, 1);
}
}
}

Programmatically open an N level self nested mat-menu component with matMenuTrigger openMenu

I am trying to make a self nested component that uses Angular Material mat-menu. I have a flyoutcomponent that is a wrapper for flyout-menu-item component, that will have a button as a matMenuTrigger for the nested component that will appear as many levels as the FeatureInput.FeatureChoices dictates. FeatureInput is an object that has FeatureChoices that may or may not contain other featurechoices etc N levels deep. Below code does not compile but it should demonstrate what I am doing. Basically I have flyout menu component as a input to a form and I am trying to load a stored answer on a form rather than select new, which I can do easily using the nested component. The desired behavior is that if the user clicks top matMenuTrigger button to open the top menu that it would expand all child menus to the menu item that matches with the FeatureInput.FeatureValue and sets the menu item _highlighted to true. I am using the menuOpen input parameter and ngChanges successfully to find the match(with I a setTimeout which cannot be right). Basically when I console.log this.trigger it is undefined. Ideally in the ngOnChange to the openMenu I would go through all menus and call openMenu on all the triggers but I cannot get access to the matMenuTrigger with ViewChild as the docs say. I get undefined. *-( All help welcome please and thanks.
Here is flyout template component.
<div>
<buttonmat-button [matMenuTriggerFor]="menu.childMenu"
(onMenuOpen)="onMenuOpen()"
(onMenuClose)="onMenuClose()">
<span [innerHTML]="featureInput.Text"></span>
</button>
<app-flyout-menu-item #menu
[featureChoicesObject]="featureInput.FeatureChoices"></app-flyout-menu-item>
</div>
And here is its .ts
import { Component, OnInit, Input, ViewChild } from '#angular/core';
import { MatMenuTrigger } from '#angular/material';
#Component({
selector: 'app-flyout',
templateUrl: './flyout.component.html',
styleUrls: ['./flyout.component.scss']
})
export class FlyoutComponent implements OnInit {
#Input() featureInput: FeatureInput
constructor() { }
ngOnInit() {
}
onMenuOpen() {
this.menuOpen = true;
}
onMenuClose() {
this.menuOpen = false;
}
}
And here is flyout-menu-item template
<mat-menu #childMenu="matMenu" [overlapTrigger]="false">
<span *ngFor="let featureChoice of featureChoices">
<span>
<button mat-menu-item [matMenuTriggerFor]="menu.childMenu">
<span [innerHTML]="featureChoice.Text"></span>
</button>
<app-flyout-menu-item #menu
[menuOpen]="menuOpen"
[featureInput]="featureInput"
[featureChoicesObject]="featureChoice.FeatureChoices"
(onOptionSelected)="someService.SomeMethod($event)"></app-flyout-menu-item>
</span>
<span *ngIf="!featureChoice.FeatureChoices">
<button mat-menu-item (click)="selectOption(featureChoice.ID)" [innerHTML]="featureChoice.Text" value="{{featureChoice.ID}}"></button>
</span>
</span>
</mat-menu>
And here is its .ts
import { Component, OnInit, Input, Output, ViewChild, EventEmitter, OnChanges, SimpleChanges } from '#angular/core';
import { MatMenuTrigger } from '#angular/material';
import { FeatureChoice } from 'app/model/feature-choice';
import { FeatureInput } from 'app/model/feature-input';
#Component({
selector: 'app-flyout-menu-item',
templateUrl: './flyout-menu-item.component.html',
styleUrls: ['./flyout-menu-item.component.scss']
})
export class FlyoutMenuItemComponent implements OnInit{
#ViewChild('menu') public menu;
#ViewChild('childMenu') public childMenu;
#ViewChild(MatMenuTrigger) public trigger: MatMenuTrigger;
#Input() featureInput: FeatureInput;
#Input() featureChoicesObject: FeatureChoice;
#Output() onOptionSelected: EventEmitter<FeatureInput> = new EventEmitter<FeatureInput>();
constructor(public solutionDataService: SolutionDataService) { }
ngOnInit() {
console.log(this.trigger);
}
ngOnChanges(simpleChanges: SimpleChanges) {
if (simpleChanges.menuOpen && simpleChanges.menuOpen.currentValue) {
setTimeout(() => {
// console.log(this.menu);
const itemsArray = this.childMenu.items.toArray();
for (let x = 0; x < itemsArray.length; x++) {
const menuItem = itemsArray[x];
if (this.featureInput.FeatureValue !== '' && menuItem._elementRef.nativeElement.value === this.featureInput.FeatureValue) {
menuItem._highlighted = true;
}
}
}, 1);
}
}
}
this.menuOpen = true;
Perhaps add menuOpen: boolean = false as an attribute at the top of your FlyoutComponent. I don't know where the value of menuOpen is saved.
the menuOpen property relates to the matMenuTrigger.
here's an example:
<button [ngClass]="{'active-icon': trigger.menuOpen}" type="button" mat-
icon-button #trigger="matMenuTrigger" [matMenuTriggerFor]="help">
<mat-icon></mat-icon>
</button>
<mat-menu #help="matMenu">
<div> textId </div>
</mat-menu>

#Input not Binding data from component

Angular2 #Input component is not Binding data from another component
DummyComponent.ts
import { Component,Input,ElementRef } from "#angular/core"
#Component({
selector: "Dummy-Selector",
template: `Hello Dummy How Are you....`,
// inputs: ["rating"]
})
export class DummyComponent {
debugger;
#Input() username: string;
}
LoginComponent.html
<input type="text" [(ngModel)]="LoginObj.username" value="user" />
<div>
<Dummy-Selector [username]='LoginObj.username'></Dummy-Selector>
</div>
Here I'm getting my Dummy-selector username data but when I insert some data in LoginObj.username via the input field - why is it not reflected?
It's not clear exactly what error you are seeing (if any) but it input binding should work with the following:
LoginComponent.ts
#Component({..})
export class LoginComponent {
LoginObj = {};
}
In DummyComponent.ts change the template to show that the username field reflects changes from the input field.
import { Component,Input } from "#angular/core"
#Component({
selector: "Dummy-Selector",
template: `Hello Dummy How Are you... {{username}}`,
})
export class DummyComponent {
debugger;
#Input() username: string;
}

Resources