@wb_by
Учусь

Что у меня не так с директивой Angular 8?

Суть задачи в том, чтобы просто при наведении на элемент меню показывался элемент (в моем случае выпадающее меню) Понимаю что это можно сделать просто с css, но я хочу научиться пользоваться кастомными директивами.

Вообщем это with-secondary-menu.directive.ts
import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[withSecondaryMenu]'
})
export class WithSecondaryMenuDirective {
  
  show: boolean = false;
  constructor(private el: ElementRef) {

    @HostListener('mouseenter') onMouseEnter() {
      this.show = true;
    }
    
    @HostListener('mouseleave') onMouseLeave() {
      this.show = false;
    }

  }

}


app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule, routingComponents } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { FooterComponent } from './footer/footer.component';
import { WithSecondaryMenuDirective } from './with-secondary-menu.directive';

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    FooterComponent,
    routingComponents,
    WithSecondaryMenuDirective
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


navbar.component.html
<nav>
    <ul>
        <li>
            <a routerLink="" class="bold">Заказать звонок</a>
        </li>
        <li>
            <a routerLink="/contacts">Наши контакты</a>
        </li>
        <li withSecondaryMenu>
            <a routerLink="/products">Прайс</a>
            <ul class="secondary-menu" [ngClass] = "{'show-menu': this.show}">
                <li>
                    <a routerLink="/products">Прайс 1</a>
                </li>
                <li>
                    <a routerLink="/products">Прайс 2</a>
                </li>
                <li>
                    <a routerLink="/products">Прайс 3</a>
                </li>
            </ul>
        </li>
    </ul>
</nav>


Сама ошибка: 11

@HostListener('mouseenter') onMouseEnter() {

src/app/with-secondary-menu.directive.ts:11:48 - error TS1005: ';' expected.

11 @HostListener('mouseenter') onMouseEnter() {
~
src/app/with-secondary-menu.directive.ts:15:32 - error TS1146: Declaration expected.

15 @HostListener('mouseleave') onMouseLeave() {

src/app/with-secondary-menu.directive.ts:15:48 - error TS1005: ';' expected.

15 @HostListener('mouseleave') onMouseLeave() {
~

Давно я ангуляр забросил... вообще не помню как и что работает. Да и не помнил вообще. Так что обьясните как чайнику пожалуйста что за проблема у меня.
  • Вопрос задан
  • 108 просмотров
Решения вопроса 1
Xuxicheta
@Xuxicheta Куратор тега Angular
инженер
У вас проблема в том, что вы методы объекта пытаетесь объявить внутри конструктора. Ангуляр тут не виноват.

Реализация:
import { Directive, TemplateRef, ViewContainerRef, OnInit, ElementRef, HostListener, Renderer2, HostBinding } from '@angular/core';

@Directive({
  selector: '[appHover]',
})
export class HoverDirective implements OnInit {
  content: NodeList;

  constructor(
    private el: ElementRef<HTMLElement>,
    private renderer: Renderer2,
  ) { }

  @HostListener('mouseenter') show() {
    this.content.forEach(node => this.renderer.setStyle(node, 'display', ''));
  }

  @HostListener('mouseleave') hide() {
    this.content.forEach(node => this.renderer.setStyle(node, 'display', 'none'));
  }

  ngOnInit() {
    this.content = this.el.nativeElement.childNodes;
    this.hide();
  }
}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы