2016-05-31 71 views
3

我想創建一個自己的信息窗口,我到澳鵬谷歌地圖類的父級的功能這個樣子的,其被通過點擊標記觸發:Angular2-追加變量未定義

updateDiv(location: Location) { 
this.selectedLocation = location; 
this.isClicked = true; 
this.ID = this.selectedLocation.id; 


console.log(this.ID) 

$(function() { 
    $('.gm-style-iw').parent().append('<div class="test"><span class="ID">'+ this.ID +'</span></div>'); 
}); 
} 

console.log顯示點擊標記的ID,但在div class='test'中顯示爲未定義。

這是爲什麼?

或者是否也可以添加您在html模板中創建的div?它看起來像這樣:

<div *ngIf="isClicked" class="infoWindow"> 
    <p>{{ selectedLocation.id }} {{ selectedLocation.content }}</p> 
</div> 

回答

1

兩件事情。

第一:正如Gunter所提到的,由於範圍的原因,您會遇到不確定的情況。使用胖箭頭功能可以解決您的問題。

第二個: 我認爲你的問題更好的解決方案將使用innerHtml。

<div [innerHtml]="myHtml"></div>

而且

myHtml: string; 
 

 

 
constructor() { 
 
    this.myHtml = '<input type="text">' 
 
}

更新! 作爲OP已經在使用該角地圖組件,最佳的解決方案已經存在與SebmGoogleMapInfoWindow

內組件的標記,你可以包括你自己的HTML:

<sebm-google-map-info-window> 
 
    <div [innerHtml]="infoW" ></div> 
 
</sebm-google-map-info-window>

而且因爲組件提供clickedMarker事件。你可以用它來插入您的自定義HTML:

clickedMarker(label: string, index: number) { 
 
    this.infoW = '<input type="text" value="' + label + '"> <hr> <button class="btn btn-success">Index = ' + index + '</button>'  
 
    }

完整的示例在這裏http://plnkr.co/edit/mG5cXP?p=preview

+0

這不是工作,這是我做過什麼: '$(」克式-iw')。親本()。追加(「

'+ '
‘+ ’
‘)' 而這其中的構造函數,但它並沒有顯示的innerHTML 'this.myHtml =’
'+ ''+ ''+ this.ID + ''+ ''+ '
」' – Sreinieren

+0

你不需要的jQuery的含量可言。 [innerHtml] =「myHtml」必須放在您的模板html中。 將其視爲模型中任何變量提供的一些html代碼的主機。 –

+0

但我將它附加到google-maps類,它覆蓋標準infoWindow:https://plnkr.co/edit/QZLs74?p=preview – Sreinieren