2016-11-27 82 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中重现吗? –