Search code examples
angular6angular-library

Accessing HTML field of Parent Component in Library's component


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!


Solution

  • 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