2016-01-13 72 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? –

相關問題