【问题标题】:angular 7 radio [attr.avlue] breaks [ngModel] functionalityangular 7 radio [attr.value] 打破 [ngModel] 功能
【发布时间】:2019-12-20 07:42:39
【问题描述】:

我有一个包含 4 个单选输入元素的列表,由 *ngFor 生成。 当我使用ngModel[attr.value]="ans.name" 时,在每个单选元素上 在我使用 value="{{ans.name}}"

之前,这不起作用

以下是破解代码示例。

<li *ngFor="let ans of question.answers; let i = index;">
  <label class="custom-radio" [attr.tabindex]="i+1" [attr.for]="'op-'+i"> {{ans.name}}
    <input type="radio" name="answer" [attr.value]="ans.name" [attr.checked]="selectedAnswer === ans.name" [attr.id]="'op-'+i" [(ngModel)]="selectedAnswer">
    <span class="checkmark"></span>
  </label>
</li>

这是工作示例。

<li *ngFor="let ans of question.answers; let i = index;">
  <label class="custom-radio" [attr.tabindex]="i+1" [attr.for]="'op-'+i"> {{ans.name}}
    <input type="radio" name="answer" value="{{ans.name}}" [attr.checked]="selectedAnswer === ans.name" [attr.id]="'op-'+i" [(ngModel)]="selectedAnswer">
    <span class="checkmark"></span>
  </label>
</li>

我真的不明白。

【问题讨论】:

    标签: javascript angular radio-button


    【解决方案1】:

    有一个官方方法可以做到这一点。使用attribute binding。这是一个简单的方法。实现方法见the docs

    import { Attribute, Component } from '@angular/core';
    
    @Component({
      selector: 'app-my-input-with-attribute-decorator',
      template: '<input type="{{type}}">'
    })
    export class MyInputWithAttributeDecoratorComponent {
      constructor(@Attribute('type') public type: string) { }
    }
    

    在父组件中:

    <app-my-input-with-attribute-decorator type="number"></app-my-input-with-attribute-decorator>
    

    【讨论】:

      【解决方案2】:

      所有 DOM 原生属性都不能使用 [attr.value] 设置,而只能使用 [value][id][name] 或任何属性。 value="{{ans.name}}" 语法也是有效的(如果它是 string 类型),但双胡须语法更适合字符串模板,在你的情况下 [value]="ans.name" 更好。

      [attr.my-attr] 语法用于自定义属性。

      【讨论】:

        【解决方案3】:

        value 是收音机的属性。您可以使用带有方括号语法的属性绑定将其绑定到组件类的属性或模板变量。您只能对原始类型数据使用插值。它有效,但不是理想的方法。

        <li *ngFor="let ans of question.answers; let i = index;"> <label class="custom-radio" [attr.tabindex]="i+1" [attr.for]="'op-'+i"> {{ans.name}} <input type="radio" name="answer" [value]="ans.name" [attr.checked]="selectedAnswer === ans.name" [attr.id]="'op-'+i" [(ngModel)]="selectedAnswer"> <span class="checkmark"></span> </label> </li>
        

        【讨论】:

          【解决方案4】:

          属性绑定用于绑定视图元素的属性属性。值是 DOM 的本机元素,不应成为属性的一部分。属性绑定主要在我们没有任何关于 HTML 元素属性的属性视图的情况下有用。

          例如在表中 td colspan 是一个属性。所以你可以使用 [attr.colspan]

          属性绑定是,从组件类传递数据并将值设置为视图中的给定元素。所以值应该是属性绑定或者sring插值

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-04-19
            • 2015-03-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-06-23
            • 2012-09-21
            • 2018-11-06
            相关资源
            最近更新 更多