【问题标题】:Angular 2: Communication between directive and host componentAngular 2:指令和宿主组件之间的通信
【发布时间】:2016-12-03 21:45:57
【问题描述】:

我有一个组件,它的模板包含“header”、“content”和“footer”div。 在内容 div 中,我设置了一个新的自定义指令,用于检查 div 元素是否溢出。直到这一步一切正常。 接下来,我想将指令中的数据溢出到它的主机组件,以便组件知道是否显示“显示更多”按钮和其他配置。

我的问题是如何从我的内部 div 的 ('content') 指令与其宿主组件进行通信?

更新 - 添加代码示例

tile.component.ts

<div class="tile" >
<div class="header">
   ...
</div>
<div class="content" checkOverflow>
   ... tile content that may be long and contains the chaeckOverflow directive ...

<div class="footer">
   ... 
</div></div>

checkOverflow.ditective.ts

import { Directive, ElementRef, AfterViewInit } from '@angular/core';

@Directive({
selector: '[checkOverflow]'
})
export class OverflowDirective implements AfterViewInit {
   constructor(private el: ElementRef) {
   }

   ngAfterViewInit(): void {

      if (this.el.nativeElement.offsetHeight < this.el.nativeElement.scrollHeight) {

          console.log('Element has overflow');
      } else {

          console.log('Element has no overflow');
      }
}

【问题讨论】:

    标签: angular angular2-directives angular2-components


    【解决方案1】:

    您可以使用EventEmitter

    Read more here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      • 2023-03-10
      相关资源
      最近更新 更多