Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set attribute inside ngfor in Angular2

Tags:

angular

Trying to set the selected attribute inside an ngFor. The code below doesn't work because browsers are dumb and checked=false will still count as checked...

So, whatever is returned needs to be true or null. I saw this guys post *ngIf for html attribute in Angular2 but I can't work with that because I need to pass a value from the for loop to the function.

I also tried setting [attr.checked] to a function like the click event but that didn't work either.

Template:

<div class="tools">
  <div class="radio-group group-{{section.name}}">
    <label *ngFor="let content of section.content" class="{{content.name}}">
      <input
        type="radio"
        name="{{section.three}}-{{section.name}}"
        value="{{content.id}}"

<!-- This is my problem -->
        [attr.checked]="content.id === section.default"
<!-- You've just pass the problem -->

        (click)="updateModel(section, content)" />
      <div class="radio">
        <span *ngIf="content.thumbnail.charAt(0) == '#'" 
           class="image" [style.background-color]="content.thumbnail">
        </span>
        <span *ngIf="content.thumbnail.length > 0 &&
                     content.thumbnail.charAt(0) != '#'" class="image">
          <img src="/thumbnails/{{section.three}}/{{content.thumbnail}}.jpg" alt="" />
        </span>
        <span *ngIf="content.thumbnail == ''" class="image"></span>
        <span class="label">{{content.displayName}}</span>
      </div>
    </label>
  </div>
</div>

Component:

import { Component, Input } from '@angular/core';
import { AService } from './a.service';

@Component({
    selector: '[radio]',
    templateUrl: 'app/newtabs/ui.radio.component.html'
})
export class UiRadioComponent {
    constructor(private aService: AService) {}

    @Input() section:any;

    updateModel(info: any, content: any ) {
           //does things but not important
        }
    }
}
like image 635
davimusprime Avatar asked Jul 18 '26 17:07

davimusprime


1 Answers

You should be able to set the attribute by simply comparing the values inline. Try:

[attr.checked]="section.default == content.id ? 'checked' : null"
like image 84
aaronburrows Avatar answered Jul 20 '26 09:07

aaronburrows