When working with Angular, we tend to create fewer directives since components can handle most cases. However, there are still situations where creating a directive is necessary :).
1 - Creating a Directive and Injecting the Router:
import { ActivatedRoute } from '@angular/router';
@Input() url : string;
constructor(private router: Router){
router.events.subscribe( (event) => {
// You can observe the route changes here :)
});
}
With this setup, you will be able to track which route you are currently on.
2 - Time to Decide Whether to Hide or Display:
You can also utilize TemplateRef and ViewContainerRef to manipulate the DOM.
import { Directive, TemplateRef, ViewContainerRef } from '@angular/core';
constructor(private route: Router,
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef){
}
3 - Wrapping It Up:
if (this.url // Show content on correct URL) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
4 - Simply attach this directive to the element you wish to control.