Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile angular component to HTML with bindings

I need to provide a solid HTML string to my maps marker baloon body.
I want to make the baloon an Angular component and use bindings and built-in directives (*ngFor, *ngIf, etc). So Im looking for a way to evaluate all bindings in component template and compile result to a string...
How to achieve this or if this approach is non-angular - what could be the pattern recommended?

// Component

import {Component} from '@angular2/core';
import {AnyThing} from './somewhere/in/my/app/anything.model.ts';

@Component({
  selector: 'my-baloon-window',
  template: `<p>This is a baloon for {{ any.name }}</p>`
})
export class MyBaloonWindowComponent {
    constructor(public something: AnyThing) {}
}


// Implementation

import {AnyThing} from './somewhere/in/my/app/anything.model.ts';
import {MyBaloonWindowComponent} from './path/to/baloon-window.component';

/* { ...some code here... } */

private createBaloonWindow(thing: AnyThing): google.maps.InfoWindow {
    return new ymap.map.BaloonWindow({
      /* I want something like this */
      content: new MyBaloonWindowComponent(thing).toString() 
      /* ^ this is what I want ^ */
    });
}
like image 656
Федор Усаков Avatar asked Oct 10 '17 10:10

Федор Усаков


2 Answers

I'm sort of surprised no one has suggested using Angular Universal -- yes, at least as of the 2.0 compatible version it rendered an entire document, but you could load your singular component into a page, render to an html string with angular universal, and then strip out the <html> tags etc.

https://github.com/angular/universal

Angular Universal is designed to render HTML on the server side, which is fundamentally about exposing the rendering engine to code without relying on the DOM.

Also of note, if you want to access the Renderer or RootRenderer directly in Angular 4, you'll have to generate a new instance using the RendererFactory -- but both of these were exposed directly in Angular 2

https://jaxenter.com/angular-4-top-features-133165.html

like image 126
tcmoore Avatar answered Nov 14 '22 04:11

tcmoore


You could try to render MyBaloonWindowComponent into hidden div and then using delay i.e. setTimeout(..., 0) or more advanced scheduling, helper service or custom event receive resulting html from injected ElementRef.

It is possible to create special component(like NgComponentOutlet) + service that will do rendering and then emit resulting html to client code.

like image 40
kemsky Avatar answered Nov 14 '22 04:11

kemsky