Skip to content

Instantly share code, notes, and snippets.

@jonrimmer
Last active August 22, 2023 17:03
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jonrimmer/eaabd619e2edeaebed83b7bc68f33daf to your computer and use it in GitHub Desktop.
Save jonrimmer/eaabd619e2edeaebed83b7bc68f33daf to your computer and use it in GitHub Desktop.
jrSwitchCases
import { Directive, Input, Host, TemplateRef, ViewContainerRef, OnInit, DoCheck } from '@angular/core';
import { NgSwitch } from '@angular/common';
@Directive({
selector: '[jrSwitchCases]'
})
export class SwitchCasesDirective implements OnInit, DoCheck {
private ngSwitch: any;
private _created = false;
@Input()
jrSwitchCases: any[];
constructor(
private viewContainer: ViewContainerRef,
private templateRef: TemplateRef<Object>,
@Host() ngSwitch: NgSwitch
) {
this.ngSwitch = ngSwitch;
}
ngOnInit() {
(this.jrSwitchCases || []).forEach(() => this.ngSwitch._addCase());
}
ngDoCheck() {
let enforce = false;
(this.jrSwitchCases || []).forEach(value => enforce = this.ngSwitch._matchCase(value) || enforce));
this.enforceState(enforce);
}
enforceState(created: boolean) {
if (created && !this._created) {
this._created = true;
this.viewContainer.createEmbeddedView(this.templateRef);
} else if (!created && this._created) {
this._created = false;
this.viewContainer.clear();
}
}
}
@blacksandsolutions
Copy link

Thanks for sharing 😄

@fermdotnet
Copy link

Cool

@Lacka90
Copy link

Lacka90 commented May 4, 2021

nice! :)

@rgoupil
Copy link

rgoupil commented Mar 28, 2022

There is one extraneous closing parenthesis at the end of line 28.

Can't wait for this feature to be addressed in Angular (angular/angular#14659), in the mean time, thanks for sharing!

@B0SS
Copy link

B0SS commented Feb 17, 2023

Hi all,

I found an other, more complex, issue.

If you have a default in you switch, the element of your default directive will be instanciated and then destroyed right after.
This is caused by the fact that we have to wait for the input property to be passed to the directive before adding the new cases in
jonrimmer directive. But in angular case directive, the case is added directly in the constructor.

To fix this issue, you simply have to set this.ngSwitch._defaultUsed to true in the constructor and then set it to false in the ngOnInit. This will prevent ngSwitch from switching to default before the cases are added.

Note that this means that at initialization, there will be a moment where the switch will not render anything even tho you specified a default element.

@taheria
Copy link

taheria commented Aug 11, 2023

Works well, thanks ❤️

@xSaraKemily
Copy link

xSaraKemily commented Aug 22, 2023

Thanks for sharing! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment