angular - 在 Angular2 的 ngfor 中设置属性

标签 angular

尝试在 ngFor 中设置选定的属性。下面的代码不起作用,因为浏览器是愚蠢的,checked=false 仍将算作已检查...

因此,无论返回什么,都必须为 true 或 null。 我看到这些人发帖 *ngIf for html attribute in Angular2但我无法使用它,因为我需要将一个值从 for 循环传递给函数。

我还尝试将 [attr.checked] 设置为类似点击事件的函数,但这也没有用。

模板:

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

组件:

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

最佳答案

您应该能够通过简单地比较内联值来设置属性。尝试:

[attr.checked]="section.default == content.id ? 'checked' : null"

关于angular - 在 Angular2 的 ngfor 中设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38508399/

相关文章:

javascript - NgRx - 减少存储的优先级和执行顺序

node.js - "ng new xxx"给出错误错误代码-4048

javascript - 数组无法正常工作,输出显示奇怪

angularjs - 如何在 Angular2 中显示和隐藏带有复选框元素的 div?

angular - Bamboo - Angular 4 应用程序如何部署

javascript - 在单页应用程序中,我们应该在内存中缓存多少数据?

Angular 2 - 在发出其他 api 请求之前首先等待身份验证 api 调用解析

javascript - 为什么我的 JavaScript 会抛出““No ' Access-Control-Allow-Origin' header is present on the requested resources”错误,而 Postman 却没有?

javascript - 如何根据 typescript 显示的动态条件更改图标?

javascript - 如何解决在 Firefox 中使用 ViewEncapsulation.Native 加载 Angular 组件的问题