如何将对象数组转换为HTML表单

时间:2019-06-14 10:37:14

标签: angular typescript angular-reactive-forms

我是Angular的初学者,遇到了问题。 我想将数据从后端传输到前端,并将其填写在HTML表单中。但是有一个错误。如果我理解正确,原因是表单生成器在查询答案到达之前被触发。 如何解决此错误?

categories.component.ts

import {Component, OnInit} from '@angular/core';
import {FormArray, FormBuilder, FormGroup} from '@angular/forms';
import {Category} from '../../../shared/models/category';
import {Router} from '@angular/router';
import {ProductsService} from '../../../shared/services/products.service';

@Component({
  selector: 'app-category',
  templateUrl: './categories.component.html',
  styleUrls: ['./categories.component.scss']
})
export class CategoriesComponent implements OnInit {

  // categories = [
  //   {id: 1, name: 'veloglasses', uaName: 'Велоокуляри'},
  //   {id: 2, name: 'skiglasses', uaName: 'Лижні окуляри'},
  //   {id: 3, name: 'frames', uaName: 'Оправи'},
  //   {id: 4, name: 'accesories', uaName: 'Аксесуари'}
  // ];
  categories: Category[];

  categoryForm: FormGroup;

  constructor(private fb: FormBuilder,
              private router: Router,
              private productService: ProductsService) {}

  ngOnInit() {
    this.productService.getCategories().subscribe(data => {
      this.categories = data;
      this.categoryForm = this.fb.group({
        categories: this.fb.array(this.categories.map(category => {this.createCategoryGroup(category), console.log(category); } ))
      });
      console.log(this.categories);
    });
  }

  createCategoryGroup(category: any = {}) {
    return this.fb.group({
      id: this.fb.control(category.id),
      name: this.fb.control(category.name),
      uaName: this.fb.control(category.uaName)
    });
  }

  addCategory() {
    this.categoriesArray.push(this.createCategoryGroup());
  }

  onSubmit() {
    this.productService.createCategory(this.categories);
    console.log(this.categoryForm.value);
  }

  removeCategory(index) {
    this.categoriesArray.removeAt(index);
  }

  get categoriesArray() {
    return (this.categoryForm.get('categories') as FormArray);
  }

}

categories.component.html

<form id="productCategories" [formGroup]="categoryForm">
  <div class="form-group" formArrayName="categories">
    <div *ngFor="let category of categoriesArray.controls; let i = index;">
      <div class="row" [formGroupName]="i">
        <input class="form-control" type="number" formControlName="id">
        <input class="form-control" type="text" formControlName="name">
        <input class="form-control" type="text" formControlName="uaName">
        <button class="btn" type="button" (click)="removeCategory(i)">Remove</button>
        <button class="btn" type="submit" (click)="onSubmit()">Update</button>
      </div>
    </div>
  </div>
  <button class="btn" type="button" (click)="addCategory()">Add Category</button>
</form>

products.service.ts

import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Product} from '../models/product';
import {Category} from '../models/category';

const header = new HttpHeaders({'Content-Type': 'application/json'});

@Injectable({
  providedIn: 'root'
})
export class ProductsService {

  constructor(private http: HttpClient) { }

  private productsUrl = 'http://localhost:8080/products';
  private categoriesUrl = 'http://localhost:8080/products/categories';

 ...

  public createCategory(category) {
    return this.http.post<Category>(this.categoriesUrl + '/add', category);
  }

  public getCategory(category) {
    return this.http.get<Category>(this.categoriesUrl + '/' + category.id);
  }

  public getCategories() {
    return this.http.get<Category[]>(this.categoriesUrl);
  }

  public deleteCategory(category) {
    return this.http.delete(this.categoriesUrl + '/' + category.id);
  }
}

1 个答案:

答案 0 :(得分:0)

您可以在加载时创建一个空表单数组,然后使用数据对其进行修补。

  ngOnInit() {
    const categoryArray = this.fb.array([])
    this.categoryForm = this.fb.group({
      categories: categoryArray
    });

    this.productService.getCategories().subscribe(data => {
      this.categories = data;
      this.categories.forEach(category => {
        categoryArray.push(this.createCategoryGroup(category)); 
        console.log(category); 
      })
    });
  }