2016-12-05 3 views
0

현재 모든 앱이 포함 된 래퍼에 클래스를 제공하려고합니다. 일반적으로 헤더가 고정되어 있거나 메뉴가 열렸을 때 같은 특정 상태를 제공하기 때문에 편리합니다.Angular2 : 지시어 변수 변경, 업데이트 요소

따라서 일부 각도의 문서를 읽는 동안 '지시문'을 사용해야합니다. 이제 나는이 모든 설정했고 그것은 다음과 같습니다

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; 
    } 
} 

을 지금이 완벽하게 작동하지만 당신은 내가 스크롤 위치에 따라 headerFixed 변수를 전환하고있어 볼 수있다. 그러나 나는 물론 함수 setClasses()을 실행할 수 있으며 작동하지만 어쨌든 구독하고/변수를보고 변경되면 자동으로 업데이트됩니까?

또는 시도하고있는 와트를 달성하는 더 좋은 방법이 있습니까?

+1

당신이 '함께 게터와'('헤더 고정') @HostBinding를 사용하려고 있나요? http://stackoverflow.com/questions/35168683/hostbinding-with-a-variable-class-in-angular2 – yurzui

+0

아, 그래, 고마워! – LVDM

+0

더 많은 것은 그것과 관련이있다. 예를 들어 지시어 selector 내에서 나는 다음과 같이 menuOpen을 토글하는 버튼을 가지고있다. 변수가 선언 된 지시어에서'(click) = "menuOpen =! menuOpen"'@HostBinding 'class.menu-open') menuOpen = false;'그러나 작동하지 않습니다. 그런 종류의 사건을 가장 잘 처리 할 수있는 아이디어가 있습니까? – LVDM

답변

2

당신이 좋아하는 @HostBinding를 사용할 수 있습니다

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

Plunker Example

+0

고마워요! 내일 아침에 일할 수 있는지 확인해 드리겠습니다. – LVDM

+0

You welc welc 오메! – yurzui