Here is the code that I have
<parent my-directive [toHide]="childRef">
<child bottom right #childRef>
<button>Some text </button>
</child >
</parent >
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');
}
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.
If
<child>
is a plain HTML element (no component) then this should work (addednativeElement
)if
<child>
is an Angular component change this lineto
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 thenativeElement
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 theread
parameter, but accessing the template variable reference from within the template doesn't provide that.However I'd suggest using
in the directive and use CSS like
to apply the styles.