angular - 為什麼 NgFor 在 DOM 中渲染 "template_bindings={}",而不是在我的組件中渲染數據綁定的元素?
當我在 DevTools 檢查資料(城市和縣市)時,它已經正確載入。模板上的所有內容也都正確載入(沒有錯誤拋出),只是 option 元素的值沒有顯示。不幸的是,因為 Angular 2 剛進入 beta 版本,語法會根據 X 博客文章的撰寫時間、Y Stack Overflow 問題的提出時間,或者你查看的 angular.io 頁面不同而有所差異。不知道我這裡缺少了什麼。
我意識到分配 value 屬性和添加文字可能有些過度,但兩者都沒有區別。
import {Component} from 'angular2/core';
import {NgFor} from 'angular2/common';
import {City, County, RegionalData} from './interfaces';
import {api} from './api.service';
@Component({
selector: 'geo-selector',
template: `
<div>
<select name="region-selector">
<optgroup label="Cities">
<option *ngFor="#city of cities" selected="selected" [value]="city.name">{{city.name}}</option>
</optgroup>
<optgroup label="Counties">
<option *ngFor="#county of counties" [value]="county.name">{{county.name}}</option>
</optgroup>
</select>
<label for="">Zip Search</label>
<input type="text" name="zip-search"/>
</div>
`,
providers: [api],
directives: [NgFor]
})
export class GeoSelector {
public cities: City[];
public counties: County[];
constructor(private _api:api) {
this.getRegions();
}
getRegions(): void {
this._api.getRegions().then(function(data: RegionalData) {
this.cities = data.cities;
this.counties = data.counties;
});
}
onSelect() {
}
}
當我在開發者工具中檢查元素時,在應該放置 option 元素的區域,我看到這個:
<!--template bindings={}-->
提示:我看到該註解是由 setBindingDebugInfo 在 angular2/ts/src/platform/dom/dom_renderer.ts 中呈現的,這“僅在調試模式下使用,用於將屬性變化序列化到註解節點,例如 佔位符。”
答案#1
getRegions 的 promise 回呼函數寫得不正確
getRegions(): void {
this._api.getRegions().then((data: RegionalData) => {
this.cities = data.cities;
this.counties = data.counties;
});
}
使用這個符號,否則 this 會指向回呼函數,而不是 GeoSelector 類別
