带有* ngFor的元素中“name”属性的Angular2绑定
我正在试验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?如何解决这个问题?
最终答案
使用([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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |