Search code examples
angularangular-directive

Angular directive template for dynamic youtube popup


I want to create directive youtube-video-popup.directive.html that will listen to clicks on the element and will create popup from template dynamically. E.g. I want this html and all methods to be embed in directive so I can just add functionality like this<a youtubeVideoPopup="aFLEAmssDfax"></a> and pass videoId to generated popup e.g.:

<div preventBodyScroll class="modal-window modal-window--dark modal-window--no-padding">
    <a href="javascript:void(0)" class="modal-window__close" (click)="closeVideoPopup()"></a>

    <div class='embed-responsive embed-responsive-16by9'>
        <iframe id="ytplayer" type="text/html" [src]="videoId" frameborder="0" allowfdivlscreen></iframe>
    </div>
</div>
<div class="modal-backdrop" (click)="toggleVideoPopup()"></div>

I dont want this to be component as it will require some extra coding including (click) handlers each time - I have a lot of various elements that can trigger youtube video popup with different layouts and styles.

Can anyone suggest a direction to move? Is it possible to achieve this with Angular 5+? I started from creating template but @Directive does not even accept templateUrl as a param.


one of the possible solutions I see for this particular youtube-popup case is to use <youtube-popup-component> directly in app.component.html and pass id to the component through the directive -> service -> component chain and show popup based on that ad, assuming only one youtube popup can be on the page at once


Solution

  • You can for example look at this repository https://github.com/pleerock/ngx-tooltip/tree/master/src. There you have some example of directive that is appending dynamically created component to component with applied [tooltip]. Basically the most important thing to do is to inject ViewContainerRef and ComponentFactoryResolver to your directive, from there you can build some component and attach it to DOM.