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
}
}
}
You should be able to set the attribute by simply comparing the values inline. Try:
[attr.checked]="section.default == content.id ? 'checked' : null"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With