侧边栏壁纸
  • 累计撰写 22 篇文章
  • 累计创建 3 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

在Directive中获取组件DOM以及实例

UUICE
2022-06-29 / 0 评论 / 0 点赞 / 932 阅读 / 1074 字

获取DOM

@angular/core 导入 ElementRefElementRefnativeElement 属性会提供对宿主 DOM 元素的直接访问权限。

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

@Directive({
  selector: '[appTest]'
})
export class TestDirective {
  constructor(
    private el: ElementRef,
  ) {
    el.nativeElement.style.backgroundColor = 'yellow';
  }
}

获取组件实例

组件已知的情况下,在自定义指令中获取组件实例

直接在constructor中注入对应组件就可以

如下面代码,通过 this.com 就可以调用组件的属性和事件

import { Directive } from '@angular/core';
import { comTest } from 'comTest';
@Directive({
  selector: '[appTest]'
})
export class TestDirective {
  constructor(
    private com: comTest
  ) {
    console.log(this.com)
  }
}

0

评论区