Trying to develop an Angular Directive that will handle various functionalities based on config input values
- Dynamically add elements to the DOM based on input values (similar to ngIf)
- Apply styling to rendered elements
- Add attribute properties such as
disabled
to elements
Based on my understanding of Angular, we can accomplish the first requirement using a Structural Directive. For the second and third requirements, we need to create an Attribute Directive. Below is the implementation for both directives
import { SomeService } from './some.service';
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({ selector: '[structuralBehaviour]' })
export class StructuralBehaviourDirective {
constructor(private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef, private someService: SomeService) { }
@Input() set structuralBehaviour(config: any) {
// Handling the logic for adding template in DOM
this.viewContainer.createEmbeddedView(this.templateRef);
}
}
Here is the Attribute Directive
import { SomeService } from './some.service';
import { Directive, ElementRef, Input, Renderer } from '@angular/core';
@Directive({ selector: '[attributeBehaviour]' })
export class AttributeBehaviourDirective {
constructor(private _renderer: Renderer, private _el: ElementRef,
private someService: SomeService) { }
@Input() set attributeBehaviour(config: any) {
// Applying style visibility property to hidden
this._el.nativeElement.style.visibility = 'hidden';
// Adding disabled attribute
this._renderer.setElementProperty(this._el.nativeElement, 'disabled', true);
}
}
Currently, I am using these directives as follows, which is working well
<button *structuralBehaviour="config" [attributeBehaviour]="config"
class="btn btn-primary">Add</button>
I'm exploring if it's possible to merge both directives into a single directive for ease of use, something like this
<button *singleBehaviour="config" class="btn btn-primary">Add</button>