默认情况下,在Angular的单选按钮组列表中检查单选按钮?

时间:2019-02-04 15:46:10

标签: html angular ngfor radiobuttonlist

我正在使用Angular 7和HTML。加载页面时,我面临选中默认单选按钮的问题。我可以获取价值,但是在加载页面时无法选中单选按钮。请任何人指导我如何解决这个问题。

StackBlitz Link

//我的ts文件

paymentModeStatus: string;
selectedValueForPaymentModeChange = 'cash';
paymentModeList: any = [];

public constructor() {}

ngOnInit() {
  this.getPaymentModeList();
}
getPaymentModeList() {
  this.paymentModeList = [{
      'checked': true,
      'name': 'Cash',
      'value': 'cash',
    },
    {
      'checked': false,
      'name': 'Pay to Accounts',
      'value': 'accounts',
    }
  ];
}

//我的html文件

<div style="font-weight: bold">Payment Mode:</div>

<label 
  style="padding: 0 5px 0 20px" 
  *ngFor="let paymentMode of paymentModeList">
  <input 
    type="radio" 
    name="paymentMode" 
    required="false"
    [(ngModel)]="paymentModeStatus" 
    [value]="paymentMode.name"
    (click)="paymentModeStatusAction(paymentMode.value)"             
    [checked]='paymentMode.checked'>
    {{paymentMode.name}}
</label>
<pre>{{ paymentModeStatus }}</pre>

2 个答案:

答案 0 :(得分:2)

由于您已指定[(ngModel)]="paymentModeStatus"[value]="paymentMode.name",因此您必须将paymentModeStatus设置为要设置为默认付款方式的name

只需将其添加到您的ngOnInit

this.paymentModeStatus = this.paymentModeList[0].name;

  

这是您推荐的Working Sample StackBlitz

答案 1 :(得分:2)

这是因为 Checked 属性不需要值

https://www.w3schools.com/tags/att_input_checked.asp

只要check属性存在,就会对元素进行检查。

从上面的链接

<form action="/action_page.php">
  <input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
  <input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>
  <input type="submit" value="Submit">
</form>

编辑 我已使用以下代码将您的html [buttons-checkbox.html]修改为显示默认选中状态

<style>
  label {
    padding: 0 5px 0 20px
  }
</style>

<div><b>Payment Mode:</b></div>

  <label *ngFor="let paymentMode of paymentModeList">

    <input 
      type="radio" 
      name="paymentMode" 
      required="false" 
      [(ngModel)]="paymentModeStatus" 
      [checked]="paymentMode.checked == 'true'"
    />

    {{paymentMode.name}} {{paymentMode.checked}}

  </label>

<pre>{{ paymentModeStatus }}</pre>
相关问题