加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

带有* ngFor的元素中“name”属性的Angular2绑定

发布时间:2020-12-17 07:52:02 所属栏目:安全 来源:网络整理
导读:我正在试验Angular2和Angular Material.我使用* ngFor让Angular生成 input我的元素.但是,在生成的网页中,生成的元素没有name属性. 这是order-form.component.html中的代码的一部分,它要求用户输入不同种类的水果的数量: md-list-item md-icon md-list-icons
我正在试验Angular2和Angular Material.我使用* ngFor让Angular生成< input>我的元素.但是,在生成的网页中,生成的元素没有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’< input>时,该元素的name属性为空,但ng-reflect-name被正确设置为apple?如何解决这个问题?
No name attribute here,but ng-reflect-name is apples

最终答案

使用([name] =“fruit”或name =“{{fruit}}”)和([attr.name] =“fruit”或attr.name =“{{fruit}}”)将一起使用.

更新

如果要使用字符串’fruit’作为name属性的值,请使用

name="fruit"

要么

name="{{'fruit'}}"

要么

[name]="'fruit'"

否则你绑定组件字段水果的值(你的组件似乎没有)

原版的

Angular默认执行属性绑定.如果你想要属性绑定,你需要明确这一点

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

要么

[name]="fruit"

也可以看看

> Angular 2 data attributes
> How to add conditional attribute in Angular 2?
> What is the difference between attribute and property?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读