如何默认选中第一个单选按钮并在 angular 中获取它的值

How to get selected 1st radio button by default and get values of it in angular

<form>
<ul>
<li class="filter-list" [ngClass]="{'active': selectedItem == item}" (click)="listCategory($event, item)" *ngFor="let item of category"><input class="pixel-radio" type="radio" [id]="item" name="category">
<label [for]="item">{{ item }}</label></li>
</ul>
</form>

这是我的HTML代码

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {

  category:string[]=["Laptop","Mobile","TV","Camera"];
  products: Products[]=[];
  selectedCategory:string;
  cart: Cart;
  brand:["Acer","Asus","Dell","HP","Lenovo"];

listCategory(event, newValue)
{
this.selectedCategory=newValue
}

但默认情况下没有值这是我在打字稿文件中的所有默认值

请检查以下 stackblitz link:

https://stackblitz.com/angular/rllllvapblod?file=src%2Fapp%2Fradio-harness-example.html

您需要将第一项的属性 'checked' 设置为 true 或 false

所以你的HTML会变成这样:

<form>
   <ul>
    <li class="filter-list" 
        [ngClass]="{'active': selectedItem == item}" 
       (click)="listCategory($event, item)" 
       *ngFor="let item of category; let i=index"
    >
           <input class="pixel-radio" 
                  type="radio" 
                 [id]="item" name="category"
                 [checked]="i===0" // Add this line
           >
           <label [for]="item">{{ item }}</label>
     </li>
  </ul>
</form>