2016-01-13 69 views
5

我想在构建Google Maps InfoWindow时能够使用Angular2模板语法。如何将Angular2组件呈现为字符串?

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

如果是这样的话,我相信我需要将组件模板串联起来。这是正确的(和可能的)?

这里是什么,我想需要做一个例子:

// 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^*/ 
    }); 
} 
+0

看看'ElementRef':HTTPS ://angular.io/docs/ts/latest/api/core/ElementRef-class.html或“ViewChild”:https://angular.io/docs/ts/latest/api/core/ViewChild-var.html – Langley

+0

我看不到创建一个Angular组件的点,然后将它转换为infowindo W上。你为什么不传递一个字符串呢?是否因为你想使用数据绑定?无论如何,这个信息在传递给infowindow后都不会被更新。 –

+1

@GünterZöchbauer - 对,我不需要数据绑定 - 模板联合体似乎比一个糟糕的stringbuilder更好。 (特别是'ngIf'和'ngFor')。那有意义吗? – drewwyatt

回答

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 
    } 
} 
+0

对不起,但它不明确。如何从组件viewChild属性注入已编译的HTML到google.maps.InfoWindow content:string? –

相关问题