0

I have created an Angular 6 library using 'ng generate library' command. This library is used in my base component after --prod build and then importing in app.module.ts of main application. The ...Component file in Library has @Input("leftPanel") leftPanel: ElementRef;

HTML Div element on base.component.html is like this: <div #leftPanel></div> And the library element using its selector :
<lib-ng-mylibrary [leftPanel]="leftPanel"> </lib-ng-mylibrary>

Library component implements AfterViewInit. In the implementation method, this code execution fails: this.leftPanel.nativeElement.style.flexBasis = '50%'; it says, this.leftPanel.nativeElement is undefined. But i can see this.leftPanel point to the div. Wonder why it does not allow this.leftPanel.nativeElement` even tho @Input leftPanel is of type 'ElementRef'?

Thanks in Advance!

Harshad
  • 3
  • 2

1 Answers1

0

Harshad

Instead of sending the parent ElementRef my feeling is that your component should have and @Output and trigger an event handled by the parent, to change the native panel width.

Doing like you reduce the coupling between the object and make them more reusable.

See docs here: https://angular.io/guide/component-interaction

Still want to use ElementRef as parameter

If you still want to send the leftPanel as a parameter, you will need an @Input() variable in your main component as well, so it can resolve <div #leftPanel> to a local variable and that variable be used in [leftPanel]="leftPanel"

cheers

hamilton.lima
  • 1,902
  • 18
  • 29
  • 1
    Thanks Hamilton. I liked the idea of Emitting events. I will try that. I changed Input variable type from ElementRef to string and from application base.component.html, sent in ID of the html element instead of ref. And then in library, used getElementById to access the html field of parent component. It works but i would prefer the suggested way of loose coupling. – Harshad Aug 30 '18 at 15:57