I have a ngbdatePicker shared component for popup and trying to use it in one of the components, but open/close (toggle) is not working.
I tried using NgbDatepicker and NgbInputDatepicker, but same issue. I'm trying to open/close the popup when pressing a button. Also if I use the "Range selection in a popup" example directly from ng-bootstrap, it works as expected. But the problem is from shared component (parent) to other components.
The error is:
ERROR TypeError: this.dateInputPicker.toggle is not a function
at DatePickerComponent.toggle (date-picker.component.ts:58:24)
Code snippet:
Shared Component HTML:
<div *ngIf="!simpleDatePicker">
<form >
<div >
<div >
<div >
<input
id="dp1"
name="datepicker"
ngbDatepicker
#dp1
[autoClose]="'outside'"
(dateSelect)="onDateSelection($event)"
[displayMonths]="2"
outsideDays="hidden"
[startDate]="fromDate!"
/>
</div>
</div>
</div>
</form>
</div>
Shared component ts:
@Component({
selector: 'app-date-picker',
templateUrl: './date-picker.component.html',
styleUrls: ['./date-picker.component.css']
})
export class DatePickerComponent implements OnInit {
...
@ViewChild('dp1') dateInputPicker: NgbInputDatepicker;
...
...
toggle(event) {
console.log(event.dp1); //logs as undefined
this.dateInputPicker.toggle(); //Errors as this.dateInputPicker.toggle is not a function
}
Popup component HTML:
<form >
<div >
<div >
<div >
<app-date-picker
name="datepicker"
ngbDatepicker
#dp1
[simpleDatePicker]="false"
[autoClose]="'outside'"
(dateSelect)="onDateSelection($event)"
[displayMonths]="2"
[dayTemplate]="t"
outsideDays="hidden"
[weekdays]="false"
[startDate]="fromDate!"
tabindex="-1"></app-date-picker>
<ng-template #t let-date let-focused="focused">
<span
[class.focused]="focused"
[class.range]="isRange(date)"
[class.faded]="isHovered(date) || isInside(date)"
(mouseenter)="hoveredDate = date"
(mouseleave)="hoveredDate = null"
>
{{ date.day }}
</span>
</ng-template>
</div>
</div>
<div >
<input
#dpFromDate
placeholder="yyyy-mm-dd"
name="dpFromDate"
[value]="formatter.format(fromDate)"
(input)="fromDate = validateInput(fromDate, dpFromDate.value)"
/>
<button dp1.toggle($event)" type="button"></button>
</div>
</div>
CodePudding user response:
this.dateInputPicker is an instance of ElementRef assigning the type as NgbInputDatepicker will not work.
- Add ngbDatepicker directive to the input element (#dp1)
- Assign the template ref as NgbInputDatepicker
- When the toggle method is called, use the dp1 template ref to toggle the popup
Shared Component HTML:
<input
id="dp1"
name="datepicker"
ngbDatepicker
#dp1="ngbDatepicker"
[autoClose]="'outside'"
(dateSelect)="onDateSelection($event)"
[displayMonths]="2"
outsideDays="hidden"
[startDate]="fromDate!"
/>
Shared component ts:
@ViewChild('dp1') dp1: NgbInputDatepicker;
toggle() {
this.dp1.toggle();
}