What I want to do using Angular is to create a "directive" that adds a something to my component, lets say a myPortlet with myHasCloseButton gives myPortlet a close button.
<myPortlet myHasCloseButton>...</myPortlet>
I found three options how to approach this and I'm not sure which one is the correct one or if I missed a better option.
Option 1: Create a directive that does something like
this.el.nativeElement.querySelector('.myCloseButton').style.visibility = 'visible';
- Presence of directive enables the button which is syntactically awesome (see above).
- Can be applied to more than myPortlets which allows a more flexible use.
- Does not allow for
*ngIf, thus forcing eachmyPortletand other components to carry a hiddenmyCloseButtonwhich feels awkward and appears to be not recommended. - Does not allow to bind to some boolean property.
Option 1a:
Just like Option 1, but give the directive an boolean @Input that switches the application of the visibility.
- Allows to bind some boolean property.
Presence of directive no longer sufficient, usage is now
...
Option 2:
Give myPortlet a boolean @Input and a *ngIf directive at the right place.
- No close-button generated where unnecessary.
- Allows for binding a boolean.
- Must be implemented seperatly for each component using it.
- Presence of directive no longer sufficient, see above.
Option 2b:
"Hackily" give a string @Input instead and check if it's empty (as that's what happens when you just give the input name without anything after) and treat it as true.
- Presence of directive enables the button which is syntactically awesome (see above).
- Does not allow to bind to some boolean property except maybe by typecasting boolean to string.
Option 3: Create a directive that actually injects the myCloseButton via something like
ElementRef.nativeElement.querySelector('.myCloseButton').addComponent(myCloseButton)
[No actual tested Syntax, just an example, not sure if addComponent is the correct function and how to use it]
- Somehow feels awkward, seems like bad practice and overcomplicated.
- Using
Elementrefis warned against in Angular Docs, appears dangerous. - Forces each
myPortletand other components to carry a hiddenmyCloseButtoncontainer. myPortlet(or other component) no longer has control over the embeddedmyCloseButton.- Due to that, it might be more difficult to achieve communication between
myPortletand the embeddedmyCloseButton(especially ofmyCloseButtonis something more complex).
So my question is: Which is the recommended approach? Am I missing any option? Any best practices? None of those options feels right.