角在父上使用指令获取嵌套元素 [英] Angular get nested element using directive on parent
问题描述
这是我拥有的代码
<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.
推荐答案
如果<child>
是纯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');
如果<child>
是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;
}
以应用样式.
这篇关于角在父上使用指令获取嵌套元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!