Search code examples
htmlangularradiobuttonlistngfor

How to get first element of md-radio-button checked within *ngFor (angular2)


Please I have this code snippet:

<md-radio-group>
      <span *ngFor="let size of item.sizes; let i = index;">
        <md-radio-button [value]="size.id" [attr.checked]="i === 0 ? '' : null">
          <span class="inline inset text-capitalize" >{{size.name}} </span>
        </md-radio-button>
      </span>
    </md-radio-group>

I want that first md-radio-button will be checked by default, that's why I've added [attr.checked]="i === 0 ? '' : null" following this question but nothing happened. Any ideas how to achieve that please ?


Solution

  • the md-radio-button being a custom component, you cannot check it with an attribute like you would do with an <input type="radio">.

    But maybe you could set a default value on your ngModel or formControl...?

    <md-radio-group [(ngModel)]="foo">
      <span *ngFor="let size of item.sizes; let i = index;">
        <md-radio-button [value]="size.id" [attr.checked]="i === 0 ? '' : null">
          <span class="inline inset text-capitalize" >{{size.name}} </span>
        </md-radio-button>
      </span>
    </md-radio-group>
    
    ngOnInit(){
      this.foo=item.sizes[0].id;
    }