Angular 使用父级指令获取嵌套元素 [英] Angular get nested element using directive on parent

查看:34
本文介绍了Angular 使用父级指令获取嵌套元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码

<parent my-directive [toHide]="childRef">

 <child bottom right #childRef>
    <button>Some text </button>
 </child >

</parent >

这里我在父元素上有 my-directive,我想访问子元素并对其应用一些样式.

Here I have my-directive on the parent element and I want to access the child and apply some style to it.

所以在我的指令中,我有以下内容.

So in my directive, I have the following.

export class MyDirective {
  @Input("toHide") localRef;

  constructor(public element:ElementRef,public renderer:Renderer) {
    console.log('Hello MyDirective Directive');
  }

  ngAfterViewInit() {
    console.log("All Transtition set");
    console.log(this.localRef);
this.renderer.setElementStyle(this.localRef, 'webkitTransition', 'transform 500ms,top 500ms');
  }

如您所见,我使用 this.renderer 来设置元素的样式,但我得到以下内容.

As you can see that I am using this.renderer to set the style on the element but I get the following.

ERROR Error: Uncaught (in promise): TypeError: el.style is undefined

在这方面的任何帮助都是适当的.

Any help in this regard is appritiated.

推荐答案

如果 是一个普通的 HTML 元素(没有组件),那么这应该可以工作(添加了 nativeElement)

If <child> is a plain HTML element (no component) then this should work (added nativeElement)

this.renderer.setElementStyle(
    this.localRef.nativeElement, 'webkitTransition', 'transform 500ms,top 500ms');

如果 是一个 Angular 组件,请更改此行

if <child> is an Angular component change this line

@Input("toHide") localRef;

@ContentChild('childRef', { read: ElementRef }) localRef;

并删除 [toHide]="childRef"

and remove [toHide]="childRef"

如果一个元素带有模板变量是一个普通的 HTML 元素,读取引用会返回一个 ElementRef 并且可以使用 nativeElement 属性访问实际元素.

If an element with a template variable is a plain HTML element, reading the reference returns an ElementRef and the actual element can be accessed using the nativeElement property.

如果它是一个组件或承载一个指令,读取引用将返回不能用于访问 DOM 元素的组件或指令实例.

If it is a component or hosts a directive, reading the reference returns the component or directive instance which can't be used to access the DOM element.

@ViewChild(ren)@ContentChild(ren) 允许使用 read 参数指定从模板变量引用返回的内容,但从模板内访问模板变量引用不提供这一点.

@ViewChild(ren) and @ContentChild(ren) allow to specify what to return from the template variable reference using the read parameter, but accessing the template variable reference from within the template doesn't provide that.

不过我建议使用

@HostBinding('class.is-transition')
isTransition:boolean false;

在指令中并使用 CSS 之类的

in the directive and use CSS like

parent[host-directive] > child {
  -webkit-transition: transform 500ms,top 500ms;
}

应用样式.

这篇关于Angular 使用父级指令获取嵌套元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆