Angular 4:默认单选按钮未被选中

时间:2018-05-31 19:07:24

标签: angular typescript

当我在component.ts中硬编码值时,我可以看到预先选择的单选按钮。但是当我尝试从sessionStorage获取值时,它不是。我可以在控制台中看到值。

我在这里做错了什么......

HTML:

<div *ngFor="let model of modelsList">
                <div>
                    {{ model.modelName }} <input type="radio" name="modelRadioGroup" [value]="model.id" [(ngModel)]="modelRadioBtn" (change)="popuplateBySearchFilter()">
                </div>

                <div class="notsotall">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </div>
            </div>


<div class="row moveright">
            <div>
                Team A <input type="radio" name="shiftRadioGroup1" value="1" [(ngModel)]="shiftRadioBtn" (change)="popuplateBySearchFilter()">
            </div>
            <div class="notsotall">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </div>
            <div>
                Team B <input type="radio" name="shiftRadioGroup2" value="2" [(ngModel)]="shiftRadioBtn" (change)="popuplateBySearchFilter()">
            </div>
        </div>

component.ts

 private modelsList: Models[];
  @Input() shiftRadioBtn: string;
  @Input() modelRadioBtn: string;
  private modelId: string;

    ngOnInit() {
          this.modelId = sessionStorage.getItem("MODEL_ID");
          this.shiftRadioBtn = "1"; //sessionStorage.getItem("MODEL_ID"); -> this working because this hard coded. If get from sessionStorage it is not pre selected
          this.modelRadioBtn = this.modelId+"";  // NOT working
          console.log("["+this.modelRadioBtn+"]"); // This prints [3]   or [1] in console

第一个单选按钮生成的html如下所示

<input _ngcontent-c1="" name="modelRadioGroup" type="radio" ng-reflect-name="modelRadioGroup" ng-reflect-value="1" ng-reflect-model="3" class="ng-untouched ng-pristine ng-valid">
<input _ngcontent-c1="" name="modelRadioGroup" type="radio" ng-reflect-name="modelRadioGroup" ng-reflect-value="3" ng-reflect-model="3" class="ng-untouched ng-pristine ng-valid">

1 个答案:

答案 0 :(得分:0)

我做错了什么。它应该是:[value]="{{model.id}}"

<div>
   {{ model.modelName }} 
   <input type="radio" 
         name="modelRadioGroup" 
         [value]="{{model.id}}" 
         [(ngModel)]="modelRadioBtn" 
         (change)="popuplateBySearchFilter()">
</div>