Skip to content

Instantly share code, notes, and snippets.

Created January 15, 2018 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/d6486243bf9429281b838a53d91d790c to your computer and use it in GitHub Desktop.
Save anonymous/d6486243bf9429281b838a53d91d790c to your computer and use it in GitHub Desktop.
import { Component, Input, AfterViewInit, ViewChild, ComponentFactoryResolver, OnDestroy, ChangeDetectorRef } from '@angular/core';
import { AdDirective } from '../ad.directive';
import { AdBanner } from '../ad-banner';
import { Ad } from '../interfaces/ad';
@Component({
selector: 'app-ad-banner',
template: `
<div class="ads">
<h3>Sistema de publicidad con Angular 5</h3>
<ng-template ad-host></ng-template>
</div>
`
})
export class AdBannerComponent implements AfterViewInit, OnDestroy {
@Input() ads: AdBanner[];
currentAddIndex: number = -1;
@ViewChild(AdDirective) adHost: AdDirective;
interval: any;
constructor(private componentFactoryResolver: ComponentFactoryResolver, private cdr: ChangeDetectorRef) { }
ngAfterViewInit() {
this.loadComponent();
this.getAds();
this.cdr.detectChanges();
}
ngOnDestroy() {
clearInterval(this.interval);
}
loadComponent() {
this.currentAddIndex = (this.currentAddIndex + 1) % this.ads.length;
const adItem = this.ads[this.currentAddIndex];
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);
const viewContainerRef = this.adHost.viewContainerRef;
viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent(componentFactory);
(<Ad>componentRef.instance).data = adItem.data;
}
getAds() {
this.interval = setInterval(() => {
this.loadComponent();
}, 3000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment