简体   繁体   English

角绑定指令到宿主父代

[英]Angular bind directive to host parent

Is it possible to limit directive to host parent? 是否可以将指令限制为主机父级? I want to bind it only to my-component . 我只想将其绑定到my-component

For example: 例如:

@Directive({
    selector: '[myDirective]'
})
export class MyDirective
{
    constructor() {  }
}

I want directive "to work" only when direct or no-direct child of my-component: 我希望指令仅在my-component的直接或非直接子代时才起作用:

<my-component>
  <ng-template myDirective></ng-template>
</my-component>

but not in this case: 但在这种情况下不是:

<any-other-component-then-my-component>      //like <div>, <tabstrip>, <panel> ...
  <ng-template myDirective></ng-template>
</any-other-component-then-my-component>

I know I can limit to host with prefixing selector: 'ng-template[myDirective]' but I need parent, so I can avoid large selector like 我知道我可以使用前缀选择器来限制主机: 'ng-template[myDirective]'但我需要使用父项,因此可以避免使用较大的选择器,例如

@Directive({
    selector: '[myComponentMyDirective]'
})

What you could do, instead of creating a selector for your directive, is to check if the parent is the component you want. 您可以做的是检查父级是否是所需的组件,而不是为指令创建选择器。

this would be something like this : 这将是这样的:

ngOnInit() {
  const el = this.el.nativeElement as HTMLElement;
  const parent = el.parentElement;
  const componentName = parent.nodeName;
  if (!componentName === 'my-component') { return; } // Stop making your directive
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM