Angular get nested element using directive on parent

巧了我就是萌 提交于 2019-12-04 18:40:42

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');

if <child> is an Angular component change this line

@Input("toHide") localRef;

to

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

and remove [toHide]="childRef"

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.

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) 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.

However I'd suggest using

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

in the directive and use CSS like

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

to apply the styles.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!