Reputation: 13
I have directive (custom *ngIf) that should hide element when width of window more 700px. When i change window size my derective is not update and element not hided but this.width
update always. Have some idea how it could fix? Here is example:
import { Directive, Input, TemplateRef, ViewContainerRef, HostListener,NgZone} from '@angular/core';
@Directive({
selector: '[ifViewportSize]'
})
export class ifViewportSize {
width:number;
constructor(private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private ngZone:NgZone) {
this.width = 600;
window.onresize = (e) => {
this.ngZone.run(() => {
this.width = window.innerWidth; // WIDTH UPDATING
});
};
}
@Input() set ifViewportSize(size: string){
if (this.width<700) {
// HERE IS NOT UPDATE
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
}
Project code is here stackblitz
Upvotes: 0
Views: 514
Reputation: 314
Without using *ngIf this can help you:
In the constructor:
constructor(private element: ElementRef /*other dependencies*/) {
// your code here
}
Outside of the constructor use this:
@HostListener('window:resize', [])
onWindowResize(): void {
if (window.innerWidth < 700) {
this.element.nativeElement.style.display = 'none';
} else {
this.element.nativeElement.style.display = 'block';
};
}
To import HostListener and ElementRef:
import {ElementRef, HostListener} from '@angular/core';
I hope this helps you.
Upvotes: 2