我正在尝试创建一个可以在html body元素中使用的指令。
该指令的目的是添加或删除一个类。
必须有一个服务来确定该类是否应该可见,因为我需要从不同的组件控制它。
问题:如何借助我的服务在我的身体元素上切换课程。
sticky-search.directive.ts
import { Directive, HostBinding, Inject, HostListener } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
import { SearchService } from '../shared/search.service';
@Directive({
selector: '[mhStickySearch]'
})
export class StickySearchDirective {
@HostBinding('class') onStickySearch() {
return this.searchService.isSearchSticky ? 'search-sticky' : '';
}
@HostListener('window:scroll', []) onWindowScroll() {
let number = this.document.body.scrollTop;
if (number >= 65) {
this.searchService.enableStickySearch();
} else {
this.searchService.disableStickySearch();
}
}
constructor(private searchService: SearchService, @Inject(DOCUMENT) private document: any) { }
}
以下指令的@Hostlistner是不触发,如果我把它放在body标签内。但是,如果我将其作为父级放置,则会触发@HostListner,但不会显示任何类。
以下是我的正文标记,AppComponent
使用作为选择器但是作为父组成
<body class="full-width" mhStickySearch>
search.service.ts
import { Injectable } from '@angular/core';
@Injectable() export class SearchService {
isSearchSticky: boolean;
enableStickySearch() {
this.isSearchSticky = true;
}
disableStickySearch() {
this.isSearchSticky = false;
}
constructor() { }
}
SearchService
中提供了AppComponent
。
该服务是从我的HeaderComponent
执行的,如下所示:
import { Component } from '@angular/core';
import { SearchService } from '../../search/shared/search.service';
@Component({
selector: 'mh-header',
templateUrl: './header.component.html'
})
export class HeaderComponent {
constructor(private searchService: SearchService) {}
openMobileMenu() {
this.searchService.enableStickySearch();
}
closeMobileMenu() {
this.searchService.disableStickySearch();
}
}
答案 0 :(得分:1)
问题在于我不能在AppComponent之外使用指令。
所以我通过删除我的指令并从我的服务中触发了vanilla javascript解决了这个问题。
import { Injectable } from '@angular/core';
@Injectable()
export class SearchService {
isSearchSticky: boolean;
enableStickySearch() {
window.document.body.classList.add('search-sticky');
this.isSearchSticky = true;
}
disableStickySearch() {
window.document.body.classList.remove('search-sticky');
this.isSearchSticky = true;
}
constructor() {
const that = this;
window.onscroll = function () {
let number = this.document.body.scrollTop;
if (number >= 65) {
that.enableStickySearch();
} else {
that.disableStickySearch();
}
};
}
}