从其他组件的html模板获取指令中标记的引用

时间:2019-07-14 00:27:48

标签: angular typescript angular2-directives angular8

每当用户单击位于标头组件的html文件中的“ a”标签上方的“ div”时,我都需要在“ div”标签中的directive.ts文件中添加引导类。

问题是@ViewChild没有获取div标签的引用,它始终是未定义的。我认为问题是引用位于不同的文件夹中,而组件位于不同的位置。

注意:directive.ts和header.component.html是不同的文件夹。

标题组件的html模板

<li class="nav-item dropdown">
     <a class="nav-link dropdown-toggle" href="#"
     id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" 
     aria-expanded="false" appDropdown> <!--directive-->
           Manage
      </a>
      <div class="dropdown-menu " aria-labelledby="navbarDropdownMenuLink"  #dropIt> <!-here i want to add a show class->
       <a class="dropdown-item" href="#">Save Data</a>
        <a class="dropdown-item" href="#">Fetch Data</a>
      </div>
     </li>

指令ts文件

import { Directive, HostBinding, HostListener, ViewChild, ElementRef, Output, OnInit } from '@angular/core';
import { HeaderComponent } from '../header/header.component';

@Directive({
  selector: '[appDropdown]'
})
export class DropdownDirective {

  isShow = false;
  @ViewChild('dropIt', {static: false}) dropIt: ElementRef; //getting reference of 'div' tag which is undefined

  @HostListener('click') toggle() {
    console.log('clicked on managed');
    console.log(this.dropIt);
    this.isShow = !this.isShow;
    if (this.isShow === true) {
      this.dropIt.nativeElement.class = 'show';
    }
  }
}

图片 directory structure of components and directive file

错误

clicked on managed 
undefined
ERROR TypeError: Cannot read property 'nativeElement' of undefined
    at DropdownDirective.toggle (dropdown.directive.ts:17)
    at Object.eval [as handleEvent] (HeaderComponent.html:16)
    at handleEvent (core.js:34789)
    at callWithDebugContext (core.js:36407)
    at Object.debugHandleEvent [as handleEvent] (core.js:36043)
    at dispatchEvent (core.js:22533)
    at core.js:33721
    at HTMLAnchorElement.<anonymous> (platform-browser.js:1789)
    at ZoneDelegate.invokeTask (zone-evergreen.js:391)
    at Object.onInvokeTask (core.js:30885)

我尝试了很多解决方案,包括一个https://stackoverflow.com/a/41371577/8132849,但没有任何效果。

0 个答案:

没有答案