如何将Angular2组件渲染为字符串?

时间:2016-01-13 17:12:40

标签: angular typescript google-maps

我希望能够在构建Google Maps InfoWindow时使用Angular2模板语法。

据我所知,这意味着将一个组件作为模板字符串传递给content构造函数对象中的InfoWindow属性。

如果是这种情况,我相信我需要对组件模板进行字符串化。这是正确的(可能的)吗?

以下是我认为我需要做的事情的一个例子:

// Component

import {Component} from 'angular2/core';
import {Thing} from './something/in/my/app/thing.model.ts';

@Component({
  selector: 'my-infowindow',
  template: `<p>This is an infowindow for {{ something.name }}</p>`
})
export class MyInfoWindowComponent {
    constructor(public something: Thing) {}
}


// Implementation

import {Thing} from './something/in/my/app/thing.model.ts';
import {MyInfoWindowComponent} from './path/to/infowindow.component';

/* { ...stuff... } */

private _buildInfoWindow(thing: Thing): google.maps.InfoWindow {
    return new google.maps.InfoWindow({
      /* v this is what I want v */
      content: new MyInfoWindowComponent(thing).toString() 
      /* ^ this is what I want ^ */
    });
}

1 个答案:

答案 0 :(得分:2)

尝试传递ElementRef angular.io/docs/ts/latest/api/core/ElementRef-class.html。

ViewChild

https://angular.io/docs/ts/latest/api/core/ViewChild-var.html

我不会为你编写代码,但这个想法是这样的:

@Component({
  selector: 'my-infowindow',
  template: `<p #kiddo>This is an infowindow for {{ something.name }}</p>`
})
export class MyInfoWindowComponent {
    @ViewChild('kiddo') viewChild;
    constructor(public something: Thing) {}
    ngOnInit(){
        yourFunction(this.viewChild); //or viewChild.innerHtml or w/e works
    }
}
相关问题