-->

Angular get nested element using directive on pare

2020-07-30 04:14发布

问题:

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.

回答1:

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.