"Fossies" - the Fresh Open Source Software Archive

Member "angular-8.2.14/aio/content/examples/dynamic-component-loader/src/app/ad-banner.component.ts" (13 Nov 2019, 1553 Bytes) of package /linux/www/angular-8.2.14.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) TypeScript source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file.

    1 // #docregion
    2 import { Component, Input, OnInit, ViewChild, ComponentFactoryResolver, OnDestroy } from '@angular/core';
    3 
    4 import { AdDirective } from './ad.directive';
    5 import { AdItem }      from './ad-item';
    6 import { AdComponent } from './ad.component';
    7 
    8 @Component({
    9   selector: 'app-ad-banner',
   10   // #docregion ad-host
   11   template: `
   12               <div class="ad-banner-example">
   13                 <h3>Advertisements</h3>
   14                 <ng-template ad-host></ng-template>
   15               </div>
   16             `
   17   // #enddocregion ad-host
   18 })
   19 // #docregion class
   20 export class AdBannerComponent implements OnInit, OnDestroy {
   21   @Input() ads: AdItem[];
   22   currentAdIndex = -1;
   23   @ViewChild(AdDirective, {static: true}) adHost: AdDirective;
   24   interval: any;
   25 
   26   constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
   27 
   28   ngOnInit() {
   29     this.loadComponent();
   30     this.getAds();
   31   }
   32 
   33   ngOnDestroy() {
   34     clearInterval(this.interval);
   35   }
   36 
   37   loadComponent() {
   38     this.currentAdIndex = (this.currentAdIndex + 1) % this.ads.length;
   39     const adItem = this.ads[this.currentAdIndex];
   40 
   41     const componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);
   42 
   43     const viewContainerRef = this.adHost.viewContainerRef;
   44     viewContainerRef.clear();
   45 
   46     const componentRef = viewContainerRef.createComponent(componentFactory);
   47     (<AdComponent>componentRef.instance).data = adItem.data;
   48   }
   49 
   50   getAds() {
   51     this.interval = setInterval(() => {
   52       this.loadComponent();
   53     }, 3000);
   54   }
   55 }
   56 // #enddocregion class