Skip to content

Instantly share code, notes, and snippets.

@PatrickJS
Last active February 11, 2017 18:17
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PatrickJS/a5bc5b3d3dd64f88e5c660f6a2df75d6 to your computer and use it in GitHub Desktop.
Save PatrickJS/a5bc5b3d3dd64f88e5c660f6a2df75d6 to your computer and use it in GitHub Desktop.
@Directive({
selector: '[universalAd],[universal-ad]'
})
class UniversalAd {
constructor(
@Attribute('id') public id: string,
public adRegistry: MyAdRegistry,
public elementRef: ElementRef,
public cdRef: ChangeDetectorRef) {
if (this.adRegistry.isRegistered(id)) {
this.adRegistry.reattach(id, this.elementRef.nativeElement);
} else {
this.adRegistry.registerElement(id, this.elementRef.nativeElement);
}
cdRef.detach();
}
ngOnDestory() {
this.adRegistry.detach(this.id, this.elementRef.nativeElement);
}
}
@Component({
template: `
<div universalAd id="importantAd"></div>
`
})
class App {
constructor() {
}
}
@NgModule({
bootstrap: [App],
declarations: [ App, UniversalAd ],
imports: [
UniversalModule
],
providers: [
{
provide: MyAdRegistry,
useFactory: () => {
var listOfAdIds = {
'importantAd': document.getElementById('importantAd')
}
var listOfClientElements = {}
return {
isRegistered: (id) => Boolean(listOfClientElements[id]),
registerElement: (id, el) => listOfClientElements[id] = el,
complete() {
Object.keys(listOfClientElements).forEach(id => {
// todo: use raf
var ngEl = listOfAdIds[id];
var serverEl = listOfClientElements[id];
document.removeChild(serverEl);
ngEl.appendChild(serverEl)
});
},
detach(id, el) {
var serverEl = listOfClientElements[id];
el.removeChild(serverEl)
},
reattach(id, el) {
var serverEl = listOfClientElements[id];
el.appendChild(serverEl)
}
};
}
}
]
})
class MainModule {
}
platformUniversalDynamic()
.bootstrap(MainModule)
.then(moduleRef => {
const adRegistry = moduleRef.injector.get(MyAdRegistry)
adRegistry.complete();
preboot.complete();
return moduleRef;
})
@pxwise
Copy link

pxwise commented Oct 31, 2016

I adapted this to a general passthrough directive. Still needs work but I have this concept working here --> https://github.com/pxwise/universal-passthrough

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment