elements with * ngFor I am experimenting with Angular2 and Angular materials. I used *ngForto make An...">

Angular2 bind attribute "name" in <input> elements with * ngFor

I am experimenting with Angular2 and Angular materials. I used *ngForto make Angular generate elements <input>for me. However, the generated element does not have an attribute on the resulting web page name.

This is the part of code in order-form.component.htmlthat asks the user for the number of different kinds of fruits:

<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>

This corresponds to 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);
  }
}

In the Chrome browser, when I right-click on "apples" <input>, the nameelement attribute is empty, but ng-reflect-nameset to applescorrect? How to solve this problem? There is no attribute name, but ng-reflect-namethere isapples

+6
1

([name]="fruit" name="{{fruit}}") ([attr.name]="fruit" attr.name="{{fruit}}") .

'fruit' name,

name="fruit"

name="{{'fruit'}}"

  [] = "''"

fruit (, -, )

Angular . ,

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

 [name]="fruit"

.

+9

Source: https://habr.com/ru/post/1015865/


All Articles