【问题标题】:Set attribute inside ngfor in Angular2在Angular2中的ngfor中设置属性
【发布时间】:2016-11-25 07:00:43
【问题描述】:

试图在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
        }
    }
}

【问题讨论】:

  • 等等,我的 ngfor 中的索引会解决这个问题吗?我认为这可以解决这个问题。我回来了!
  • 不,这很愚蠢,没有帮助。

标签: angular


【解决方案1】:

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

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

【讨论】:

  • 啊,我试过了,但我的代码肯定有其他问题,就像一个非常不聪明的人。
猜你喜欢
  • 2016-09-07
  • 2018-03-09
  • 1970-01-01
  • 1970-01-01
  • 2016-11-02
  • 1970-01-01
  • 2017-08-10
  • 2019-05-18
  • 2017-07-24
相关资源
最近更新 更多