0

I've written a directive that hides an element depending on screen size. When the page loads the element that is supposed to be hidden is being initialised.

This is my directive

mobile-only.directive.ts

@Directive({
  selector: '[appMobileOnly]'
})
export class MobileOnlyDirective {

  constructor(private el: ElementRef) {
    this.displayElement(window.innerWidth < 992);
  }

  displayElement(isMobile) {
    if (isMobile) {
      this.el.nativeElement.style.display = 'block';
    } else {
      this.el.nativeElement.style.display = 'none';
    }
  }
}

It is implemented like this

<div appMobileOnly>
  <app-brochure-mobile></app-brochure-mobile>
</div>

The directive behaves as expected in that the component isn't rendered to the screen, however the ngOnInit function in the component is being fired. Any idea why this might be happening?

abyrne85
  • 1,370
  • 16
  • 33
  • 2
    This behaviour would be better implemented with CSS media queries-- no need to use a directive here – user184994 Aug 24 '18 at 11:08
  • That's what I was afraid of. I had media queries but for some reason I thought a directive would be a better way to go – abyrne85 Aug 24 '18 at 11:12
  • 1
    I'd argue if it *can* be done with CSS, it *should* be done with CSS – user184994 Aug 24 '18 at 11:13
  • the use of angular cdk MediaMatcher can help you in this scenario (plus one it if it does :D): https://stackoverflow.com/questions/35527456/angular-window-resize-event/48841964#48841964 – Stavm Aug 24 '18 at 11:16
  • Don't use it in your contrsuctor, use it in `ngOnInit()`. Also, to display/hide, consider using `ViewContainerRef`, not CSS style. Finally, as other people said, media queries are the way to go. –  Aug 24 '18 at 11:20

1 Answers1

1

You are inserting your component into the DOM and only hiding it visually, so ngOnInit fires. You could work with ngIf or other structural directive but CSS media queries are the way to go in this scenario. BTW your code doesn't account for window resizes.

Tomasz Błachut
  • 2,368
  • 1
  • 16
  • 23