0

I'm currently trying to give classes to an wrapper that contains all of my app, i usually find this handy for giving certain states like when the header is fixed, or the menu's are opened etc.

So upon reading through some the docs of angular i should probably use an 'Directive'. Now i got this all set up and it looks like this:

constructor(private router:Router, @Inject(DOCUMENT) private document:Document, el:ElementRef, renderer:Renderer) {
    this.setClasses(el, renderer);
}

setClasses(el:ElementRef, renderer:Renderer) {
    renderer.setElementClass(el.nativeElement, 'header-fixed', this.headerFixed);
}

@HostListener("window:scroll", [])onWindowScroll() {
    let number = this.document.body.scrollTop;

    if (number > 100) {
        this.headerFixed = true;
    } else if (this.headerFixed && number < 10) {
        this.headerFixed = false;
    }
}

Now this is working perfectly but as you can see i'm toggling the headerFixed variable depending on scroll position. However i could of course run the function setClasses() again and it will work but is there anyway to subscribe/watch the variable and update automatically when changed?

Or is there even a better way of achieving wat i'm trying to do?

17
  • 1
    Have you tried to use @HostBinding('header-fixed') together with getter? stackoverflow.com/questions/35168683/… Commented Dec 5, 2016 at 14:31
  • Ah yeah that works thanks! Commented Dec 5, 2016 at 14:53
  • 1 more thing, it's sort of related, for example within the directive selector i have an button that toggles menuOpen like: (click)="menuOpen = !menuOpen" in the directive the variable is declared like: @HostBinding('class.menu-open') menuOpen = false; but it doesn't work. Any idea hoe to best handle those kind of events? Commented Dec 5, 2016 at 14:56
  • What about using getter? Commented Dec 5, 2016 at 14:58
  • Could you post an example link? Would be appreciated, also if you post an answer i'll accept it. Commented Dec 5, 2016 at 15:00

1 Answer 1

2

You can use @HostBinding like:

@HostBinding('class.header-fixed') get myClass() { 
  return someCondition; 
}

Plunker Example

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Will check tomorrow morning of i can get it to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.