如何向自定义的mat-datepicker-header添加关闭按钮 [英] How to add close button to customized mat-datepicker-header

查看:59
本文介绍了如何向自定义的mat-datepicker-header添加关闭按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular材料中的UI组件.

I am using this UI component from the Angular material.

https://material.angular.io/components/datepicker/overview#customizing-the-calendar-header

我想在自定义标题中添加关闭按钮,但这似乎还不可能.

I want to add close button the custom header but it seems not possible yet.

至少我想从日期选择器标头组件中获取输出事件.

At least I would like to get output event from the date picker header component.

推荐答案

由于 MatDatepicker MatCalendarHeader 是两个单独的组件,因此需要在这些组件之间传递数据使用 EventEmitter 或通过使用服务使用 BehaviourSubject .

As the MatDatepicker and MatCalendarHeader are two separate components, you will need to pass data between the components using an EventEmitter, or with BehaviourSubject through the use of a service.

在此示例中,我将利用服务.首先,您可以创建一个名为 calendar-service.ts 的服务,该服务将用于在组件之间共享数据.在本课程中,我们将使用 BehaviourSubject 发出更新后的布尔值,该值将指示日期选择器应打开还是关闭.

For this example, I will make use of a service. First, you may create a service called calendar-service.ts, which will be used to share data between components. Within this class, we will make use of BehaviourSubject to emit the updated boolean value which will denote if the datepicker should be open or close.

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class CalendarService {

  closeCalendarSource = new BehaviorSubject<boolean>(false);
  isCloseCalander = this.closeCalendarSource.asObservable();

  constructor() { }

  closeCalander(message: boolean) {
    this.closeCalendarSource.next(message)
  }

}

在您的 MatCalendarHeader 模板上,您应该添加一个绑定到click事件的按钮,这将触发关闭日期选择器的操作

On the template for your MatCalendarHeader, you should add a button which is binded to the click event, which will trigger the action to close the datepicker

<button mat-icon-button (click)="closeCalendar()" >
  <mat-icon>close</mat-icon>
</button>

在header的component.ts上,

And on the component.ts for the header,

constructor(
  private calendarService: CalendarService) {
}

closeCalendar() {
  this.calendarService.closeCalander(true);
}

在使用 MatDatepicker 的主要组件上,您将预订可观察对象,它将从标头组件中发出当前值.

On the main component that uses the MatDatepicker, you will subscribe to the observable which will emit the current value from the header component.

@ViewChild('picker', { static: false}) picker;
exampleHeader = ExampleHeader;

constructor(private calendarService: CalendarService) {}

ngOnInit() {
  this.calendarService.isCloseCalander.subscribe(isClose => {
    if (isClose) {
      this.picker.close();
    }
  });
}

我已经在上创建了完整的演示这里.

这篇关于如何向自定义的mat-datepicker-header添加关闭按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆