在Directive中获取组件DOM以及实例
获取DOM
从 @angular/core 导入 ElementRef。ElementRef 的 nativeElement 属性会提供对宿主 DOM 元素的直接访问权限。
1import { Directive, ElementRef } from '@angular/core';23@Directive({4 selector: '[appTest]'5})6export class TestDirective {7 constructor(8 private el: ElementRef,9 ) {10 el.nativeElement.style.backgroundColor = 'yellow';11 }12}
获取组件实例
直接在constructor中注入对应组件就可以
如下面代码,通过 this.com 就可以调用组件的属性和事件
1import { Directive } from '@angular/core';2import { comTest } from 'comTest';3@Directive({4 selector: '[appTest]'5})6export class TestDirective {7 constructor(8 private com: comTest9 ) {10 console.log(this.com)11 }12}13
暂无评论,来抢沙发吧。