2016-11-27 83 views
1

我必須做登錄,我需要選擇選項。我能幫助那些我犯錯的人嗎? 有我的代碼選擇Angular2

@Component({ 
    moduleId: module.id, 
    selector: 'tenants', 
    template:`<select name="repeatSelect" id="repeatSelect" [(ngModel)]="model.tenant"> 
     <option *ngFor="let tenant of tenants" value="{{tenant.abbr}}">{{tenant.name}}</option> 
    </select>` 
}) 



export class TenantComponent implements OnInit { 
    model: any = {}; 
    loading = false; 
    error = ''; 
    public tenants: Tenant[]; 

    constructor(

     private tenantService: TenantService) { } 

    setTenant(){ 
     //if you're on older versions of ES, use for-in instead 
     var tenant = this.tenants.find(t => t.name); 

     if(tenant) { this.model.tenant = tenant; } 
    } 

    ngOnInit() { 
     this.loading = true; 

     this.tenantService.tenants() 
      .subscribe((result : Tenant[]) => { 
       this.tenants = result; 
      }); 
    } 
} 

然後我插入登錄模板。

如果我選擇其中一個選項。在側面的HTML是enter image description here

我選擇了選項後發送了登錄請求。它不工作

感謝

+0

你還是使用:'[值] = 「tenant.abbr」',而不是'值=」 {{tenant.abbr}}「' – Maxime

+0

如果'tenant.abbr'是一個字符串值,那應該沒有關係。 –

回答

0
setTenant(){ 
     //if you're on older versions of ES, use for-in instead 
     var tenant = this.tenants.find(t => t.name); 

     if(tenant) { this.model.tenant = tenant; } 
    } 

的這部分代碼看起來很奇怪。

this.tenants.find(t => t.name)錯過了一些布爾表達式。您需要將t.name與您選擇的名稱(如t.name == selectedName)進行比較。這樣的租客將永遠是null,因爲find期望一些布爾表達式來找到一些東西!

+0

我不使用這部分代碼。我忘了刪除它 – Gioli

+0

我們錯過了一些信息。你的model.tenant會發生什麼?登錄時是否爲空?選擇值後,登錄模板會發生什麼? – lastWhisper

+0

我應該在哪裏登錄?我刪除了setTenant()方法。我的登錄有租戶的用戶名,密碼和屬性Tenant(這是一個對象)登錄.service.ts中的 – Gioli

0

[(ngModel)]="model.tenant"所指一個Tenant對象但value="{{tenant.abbr}}"指的是一個字符串。

,我認爲它應該是

template:` 
<select name="repeatSelect" id="repeatSelect" [(ngModel)]="model.tenant"> 
    <option *ngFor="let tenant of tenants" [ngValue]="tenant">{{tenant.name}}</option> 
</select>` 

[ngValue]允許使用對象的值與<option>

+0

仍然記錄tenant作爲andefined – Gioli

+0

很難說,沒有更多信息。你可以在Plunker中重現嗎? –