首页 > 解决方案 > 选择角度 6 中的默认单选按钮

问题描述

我是 Angular 的新手。在这里需要一些帮助。两个文本字段有两个单选按钮:

<div class="col-1">
 <label class="radio-container mb-0 mt-1">&nbsp;
   <input id="Page_Color" name="Page_Color" type="radio" [(ngModel)]='Br.Page_IsGraphic'
                      [value]='false' (change)="updateRadioChangeValToObj('Page_IsGraphic','Page_IsGraphic','Page_GraphicName','Page_Color')">
    <span class="checkmark"></span>
 </label>
</div>


<div class="col-1">
   <label class="radio-container mb-0 mt-1">&nbsp;
      <input id="IsGraphic" name="IsGraphic" type="radio" (change)="updateRadioChangeValToObj('Page_IsGraphic','Page_Graphic','Page_GraphicName','PageColor')"
                         [(ngModel)]='Br.Page_IsGraphic' [value]='true'>
     <span class="checkmark"></span>
   </label>
 </div>

[(ngModel)]='Br.Page_IsGraphic'Br.Page_IsGraphic 中,值为真或假,这是动态的,并且我认为单选按钮正在被选中。如果为真,则选择第二个单选按钮,如果为假,则选择第一个单选按钮。现在必须根据要求删除第一个文本字段,并且我希望始终默认选择第二个单选按钮。Br.Page_IsGraphic 值应在执行此代码之前设置为 true 才能正常工作?还是有其他方法。我试过[checked]="true"了,但没有奏效。

标签: javascriptangular

解决方案


据我了解,您有两个与两个文本字段相关联的单选按钮,并且想要显示基于单选按钮的文本字段是否被选中

.html 文件

<input type="radio" [checked] = "isFirst === true" (change)="markFirst()"/> First
<input type="radio"  [checked] = "isSecond === true" (change)="markSecond()"/>Second
<br><br>
<input type="text" placeholder="First" *ngIf="isFirst"/>
<br><br>

<input type="text" placeholder="Second" *ngIf="isSecond"/>

.ts 文件

export class AppComponent  {
  isFirst = false
  isSecond = false

  markFirst(){
    this.isFirst = true
   // this.isSecond = false If you want second to hide if one is shown
  }

  markSecond(){
    this.isSecond = true
   // this.isFirst = false If you want second to hide if one is shown
  }
}

工作链接

https://stackblitz.com/edit/angular-jkqvqz


推荐阅读