For this, we add a private calculateDateRange method to our CustomRangePanelComponent. It expects a rangeName parameter and converts it into a [start, end] tuple of generic type D (remember, this is the generic date type also used in the custom header component). We use a switch statement to differentiate between all range names. The specific calculations use various DateAdapter methods, but are not that interesting and can be looked up in the linked repository.
Remarkable is line 26, which showcases another benefit from using CustomPreset instead of string as parameter type: we can instruct the compiler to fail compilation, if we don’t provide a case definition for each possible rangeName value! This is called an exhaustiveness check and takes advantage of the never type. rangeName has type never, if every possible value is handled in the switch. It is the “impossible” type, so returning it doesn’t change the return type of the method ([start: D, end: D]). If we would add another range value, e.g ‘next year’, to our customPresets array, though, the CustomPreset type would be changed (| ‘next year’ would be added to the type union). This results in the switch to not handle ‘next year’ and thereby changing rangeName‘s type from never to ‘next year’. We would get a compiler error which reminds us to extend our calculateDateRange method ????️.
Second on the list was to set the calculated start and end dates and close the picker. How do we get access to the picker? Dependency injection! Remember, that our CustomRangePanelComponent is a child of ExampleHeaderComponent, which in turn is a child of the Material picker. So we can inject it in our constructor: