Angular 2 - 以反应形式显示对象数组

时间:2018-01-09 15:51:24

标签: angular angular-reactive-forms

我很难以角度2反应形式显示一系列配方成分延迟对象。我的组件从另一个组件接收一个配方对象数组(@Input()s_ingredients:Ingredient [])。我无法弄清楚如何在html中显示所有不同的成分。不知道有人可以帮我吗?

以下是我的组件ts代码: -

<Location /wp-admin/>
<IfModule mod_headers.c>
Header always unset  Content-Security-Policy
Header unset Content-Security-Policy
Header set Content-Security-Policy " default-src 'self' ps.w.org;" 
</IfModule>

</Location>

以下是我的HTML: -

import { Component, Input, Output, EventEmitter, OnInit, ElementRef } from '@angular/core';
import { FormArray, FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { Observable } from 'rxjs/Observable';

import { Ingredient } from '../ingredient';
import { IngredientDetailService } from '../ingredient-detail.service';


@Component({
  selector: 'app-recipe-ingredients-details',
  templateUrl: './recipe-ingredients-details.component.html',
  styleUrls: ['./recipe-ingredients-details.component.css'],
  providers: [IngredientDetailService]
})

export class RecipeIngredientsDetailsComponent implements OnInit {

  create_recipe_ingredient_detail_form: FormGroup;
  ingredients_arr: Ingredient[] = [];

  // @Output will tell the parent component (AppComponent) that an event happened in this component
  @Output() show_read_recipes_event = new EventEmitter();

  constructor(
    private formBuilder: FormBuilder,
    private ingredientDetailService: IngredientDetailService

  ) {  }

  @Input()
  r_id: number;

  @Input()
  s_ingredients: Ingredient[];

  buildIngredientDetails(): FormArray{
    return <FormArray>this.create_recipe_ingredient_detail_form.get('s_ingredients');
  }

  ngOnInit() {
    this.create_recipe_ingredient_detail_form = this.formBuilder.group({
      s_ingredientDetails: this.formBuilder.array([ this.buildIngredientDetails() ])
    });

    this.create_recipe_ingredient_detail_form = this.formBuilder.group({
      s_ingredientDetails: this.formBuilder.array(
        this.s_ingredients.map(x => this.formBuilder.group({
          ingredient_name: [x.ingredient_name, [Validators.required]]
        }))
      )
    })

  }


  createRecipeIngredientDetails(): void {
    this.ingredientDetailService.createRecipeIngredientDetails(this.create_recipe_ingredient_detail_form.value)
      .subscribe(
        ingredientDetail => {
          console.log(ingredientDetail);

          this.show_read_recipes_event.emit(
            { title: "Recipe Ingredients details" }
          );
        },
        error => console.log(error)
      );
  }

}

看我的表格(截图): -

enter image description here

1 个答案:

答案 0 :(得分:0)

此代码看起来不错,除了:

<input type="text" id="{{ingredient.ingredient_name}}" />

id不用于在输入字段中显示文本。

相反,请使用:

<input type="text" value="{{ingredient.ingredient_name}}" />

或:

<input type="text" [ngModel]="ingredient.ingredient_name" />