Last active
February 11, 2017 18:17
-
-
Save PatrickJS/a5bc5b3d3dd64f88e5c660f6a2df75d6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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; | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I adapted this to a general passthrough directive. Still needs work but I have this concept working here --> https://github.com/pxwise/universal-passthrough