Reputation: 4765
I have a directive that either shows or hides a sidebar on click. I want to create an option to show the sidebar or hide the sidebar on i.
My component.html:
<button class="sidebar-minimizer" type="button" appSidebarMinimizer [minimizeSide] = "open" appBrandMinimizer></button>
I created a property [minimizeSide] = "'open'"
My component.ts
export class AppSidebarMinimizerComponent {
open = "open";
}
My directive:
@Directive({
selector: '[appSidebarMinimizer]'
})
export class SidebarMinimizeDirective {
@Input() minimizeSide:string;
constructor() {
if (this.minimizeSide == "open"){
document.querySelector('body').classList.toggle('brand-minimized');
}
}
@HostListener('click', ['$event'])
toggleOpen($event: any) {
$event.preventDefault();
document.querySelector('body').classList.toggle('sidebar-minimized');
}
}
The click function works fine but it doesn't work while init. What am I missing?
Upvotes: 0
Views: 41
Reputation: 38209
Here the reason to your problem are listed below:
@Input
field will be updated when first change detection got executedOnChanges
=> OnInit
and so on)of itself. So you won't get value bound to @Input
unless OnChange
life hook of your directive got executed. You can move the initialization code block to directive's OnInit
life hook.
constructor() { }
ngOnInit() {
if (this.minimizeSide == "open"){
document.querySelector('body').classList.toggle('brand-minimized');
}
}
Upvotes: 1