Search code examples
htmlangularradio-buttonangular8

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>

This is my HTML CODE

@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
}

But by default value is not coming in it This is my all default values in typescript file


Solution

  • Please check the following stackblitz link:

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

    You need to have the attribute 'checked' to true or false for the first item

    So your HTML will become like this:

    <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>