angular2怎样根据接口获取的值来选中input[radio]和select?

angular2怎样根据接口获取的值来选中input[radio]和select?

阅读 6.5k
4 个回答

app.html

<select [(ngModel)]="comId">
  <option [value]="c.id" *ngFor="let c of comIdList">{{c.name}}</option>
</select>
<div>
  <label *ngFor="let t of typeList">
    <input type="radio" (change)="type=t.id" name="type" [checked]="type===t.id">{{t.name}}
  </label>
</div>

app.component.ts

@Component({
    selector: 'app',
    templateUrl: 'src/app.html'
})
export class AppComponent implements OnInit {
    comIdList:any = [
        {id: 1, name: '中国公司'},
        {id: 2, name: '美国公司'},
        {id: 3, name: '德国公司'}
    ];

    typeList:any = [
        {id: 1, name: '类型A'},
        {id: 2, name: '类型B'}
    ];
    
    comId:number;
    type:number;

    constructor() {
    }

    ngOnInit() {
        setTimeout(()=> {
            this.comId = 3;
            this.type = 2;
        }, 1000);
    }
}

先遍历下接口获取到的值 if(true){selectbox[i]= checked}

1楼写的挺好的,补充一下,其实不需要用checked属性也是可以的,

<label *ngFor="let t of typeList">
    <input type="radio" name="type" [(ngModel)]="type" [value]="t.id">{{t.name}}
</label>

    ngOnInit() {
        setTimeout(()=> {
            this.type = 2;
        }, 1000);
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题