My goal with Angular is to create a "directive" that can add functionality to my component, specifically adding a myPortlet
with a close button when using the directive myHasCloseButton
.
<myPortlet myHasCloseButton>...</myPortlet>
In exploring how to achieve this, I have come across three options but am unsure of the best approach or if there might be a better alternative.
Option 1: Develop a directive that would do something like
this.el.nativeElement.querySelector('.myCloseButton').style.visibility = 'visible';
- The presence of the directive makes enabling the button syntactically pleasing (as shown above).
- This can be applied to multiple instances of myPortlets for more flexibility.
- However, it does not allow for the use of *ngIf, leading to each myPortlet and other components having to carry a hidden myCloseButton which may not be recommended.
- It also does not support binding to a boolean property.
Option 1a: Similar to Option 1, but with an additional boolean @Input in the directive to control visibility.
- Allows for binding to a boolean property.
- No longer solely reliant on the presence of the directive - usage changes accordingly.
Option 2: Utilize a boolean @Input in myPortlet along with the *ngIf directive in the appropriate location.
- Prevents unnecessary generation of close buttons.
- Supports binding to a boolean value.
- Needs to be implemented separately for each component that uses it.
Option 2b: Using a string @Input in a somewhat "hacky" way to mimic a boolean check.
- Syntax for enabling the button remains concise.
- Limits the ability to directly bind to a boolean property, although typecasting could potentially work.
Option 3: Create a directive that injects the myCloseButton directly into the component structure.
this.el.nativeElement.querySelector('.myCloseButton').addComponent(myCloseButton)
- Feels complex and possibly against best practices.
- Directly manipulating the DOM with ElementRef goes against Angular's recommendations and can be risky.
- Compels each myPortlet to include a hidden myCloseButton container.
- Limits the control that myPortlet has over the embedded myCloseButton.
- Makes communication between myPortlet and myCloseButton more challenging, especially if myCloseButton is a complex entity.
Given these considerations, I am seeking guidance on the recommended approach. Are there any options I have overlooked? Any best practices I should consider? None of the current options feel optimal to me.