【问题标题】:Angular2 binding of "name" attribute in <input> elements with *ngFor<input> 元素中的“name”属性与 *ngFor 的 Angular2 绑定
【发布时间】:2017-08-10 05:49:31
【问题描述】:

我正在试验 Angular2 和 Angular Material。我使用*ngFor 让Angular 为我生成&lt;input&gt; 元素。但是,在生成的网页中,生成的元素没有name 属性。

这是order-form.component.html中的部分代码,要求用户输入不同种类水果的数量:

<md-list-item>
  <md-icon md-list-icon>shopping_cart</md-icon>
  <md-input-container *ngFor="let fruit of fruits" class="fruit-input">
    <input mdInput [(ngModel)]="order[fruit]" [placeholder]="capitalize(fruit)" 
           [id]="fruit" name="{{fruit}}" required value="0" #fruitInput 
           (input)="onInput(fruitInput)">
  </md-input-container>
</md-list-item>

这是对应的order-form.component.ts

import { Component, OnInit } from "@angular/core";
import { Order } from "app/order";
import { PAYMENTS } from "app/payments";
import { OrderService } from "app/order.service";

@Component({
  selector: 'app-order-form',
  templateUrl: './order-form.component.html',
  styleUrls: ['./order-form.component.css']
})
export class OrderFormComponent implements OnInit {

  order = new Order();

  payments = PAYMENTS;

  fruits: string[] = [
    'apples',
    'oranges',
    'bananas'
  ];

  constructor(public service: OrderService) {
  }

  ngOnInit() {
  }

  get totalCost() {
    return this.service.getTotalCost(this.order);
  }

  onFocus(element: HTMLElement) {
    element.blur();
  }

  onSubmit() {
    console.log('onSubmit');
  }

  onInput(element: HTMLInputElement) {
    console.log(element);
    if (!this.service.isValidIntString(element.value)) {
      window.alert(`Please input a correct number for ${element.name}`);
      element.value = '0';
    }
  }

  capitalize(str: string): string {
    return this.service.capitalize(str);
  }

  get debug() {
    return JSON.stringify(this.order, null, 2);
  }
}

在Chrome浏览器中,当我右键单击'apples'&lt;input&gt;时,元素的name属性为空,但ng-reflect-name设置为apples正确吗?如何解决这个问题? No name attribute here, but ng-reflect-name is apples

【问题讨论】:

  • 您是否遇到任何错误?
  • @Aravind 从下面的控制台,没有错误。

标签: angular input angular-material2 ngfor


【解决方案1】:

最终答案

同时使用([name]="fruit"name="{{fruit}}")和([attr.name]="fruit"attr.name="{{fruit}}")会起作用。

更新

如果您想使用字符串'fruit' 作为name 属性的值,请使用

name="fruit"

name="{{'fruit'}}"

[name]="'fruit'"

否则,您将绑定组件字段 fruit 的值(您的组件似乎没有)

原创

Angular 默认进行属性绑定。如果您想要属性绑定,则需要明确说明

 attr.name="{{fruit}}" (for strings only)

 [name]="fruit"

另见

【讨论】:

  • 当我使用attr.name="{{fruit}}" 时,浏览器会给我错误:如果在表单标签中使用了 ngModel,则必须设置名称属性或必须在 ngModelOptions 中将表单控件定义为“独立” .当我使用[name]="fruit" 时,结果根本没有变化。
  • 那么问题出在别的地方。所以你实际上并不关心name 属性被添加到&lt;input&gt;,你只是想让ngModel 工作?
  • 我想你其实想要name="fruit"
  • ngModel 正在工作。没有任何问题。当我输入任何东西时,底部的 json 字符串会相应地改变。我想要的是将name 属性添加到input 元素中。谢谢!
  • 对不起,我想要的是'apples',nameapples,对于oranges,名称是oranges,等等。如果我更改name="fruit",则name 属性仍未显示。
猜你喜欢
  • 2017-11-29
  • 2016-07-15
  • 2016-11-02
  • 2017-02-05
  • 1970-01-01
  • 2016-11-05
  • 1970-01-01
  • 2016-11-25
  • 2015-09-28
相关资源
最近更新 更多