模板在Angular2中的开关上设置为初始状态

时间:2016-08-14 07:28:43

标签: angular angular2-template

我在我的代码中使用模板标签进行动态渲染,它工作得很好但是当我在模板中实现复选框时,它们会在切换到其他模板时设置为初始状态,并返回到实现复选框的模板。根据代码最初它们是未经检查的,当我检查它们并切换到yourteam部分时,对象出现在该部分中,但是当我回到击球手时,即使我没有取消选中它们也未经检查。

team.component.html

<ul class="fields-heading">
    <li class="fields"> <a (click)="selectMode='yourteam'"      [class.active]="selectMode=='yourteam'">YourTeam</a></li>
    <li class="fields"> <a (click)="selectMode='batsman'" [class.active]="selectMode=='batsman'"> Batsman</a></li>    

</ul> 

<div [ngSwitch]="selectMode">
<template [ngSwitchWhen]="'yourteam'"> Your Team
<li *ngFor="#value of checked">{{value}}</li>

 </template>
 <template [ngSwitchWhen]="'batsman'" >         
     <div  *ngFor="#player of players; #i=index" >
    <div *ngIf="player.type=='batsman'">
         <form class="controls-stacked">
                <label class="control checkbox">  
                <input type="checkbox" (change)="updateChecked(player,$event)">
                <span class="control-indicator"></span>
                {{ player.name }}
                </label>            
            </form>        
     </div>
 </div>         
  </template>

team.component.ts

 export class TeamComponent  {
    selectMode = 'batsman';
    checked: string[] = [];
    players=[{
    "id": 1,
    "name" : "player1",
    "type": "batsman",
    "team" : "team1"
     },{ 
     "id": 2,
     "name" : "player2",
     "type": "batsman",
     "team" : "team1"

     }];

    updateChecked(player,event){ 

    var index = this.checked.indexOf(player);
    if(event.target.checked){
        if(index===-1){
            this.checked.push(player);
        }
    }else{
        if(index!==-1){
            this.checked.splice(index,1);
        }
      }
     }
    }

1 个答案:

答案 0 :(得分:0)

您的复选框值未绑定到任何变量。我会建议如下:

<强> team.component.html

<input type="checkbox" [(ngModel)]="player.checked"(ngModelChange)="updateChecked(player,$event)">

使用(ngModelChange)代替(change)。 Angular 2无法可靠地检测到(change)。参考:https://github.com/angular/angular/issues/10038#issuecomment-232366532

<强> team.component.ts

 export class TeamComponent  {
    selectMode = 'batsman';
    checked: string[] = [];
    players=[{
    "id": 1,
    "name" : "player1",
    "type": "batsman",
    "team" : "team1",
    "checked" : false
     },{ 
     "id": 2,
     "name" : "player2",
     "type": "batsman",
     "team" : "team1"
     "checked" : false
     }];

    updateChecked(player,event){ 

    var index = this.checked.indexOf(player);
    if(event.target.checked){
        if(index===-1){
            this.checked.push(player);
        }
    }else{
        if(index!==-1){
            this.checked.splice(index,1);
        }
      }
     }
    }