簡體   English   中英

使用 Angular 8 反應式 forms 捕獲表單輸入

[英]capturing form inputs with Angular 8 reactive forms

我想讓我的 forms 按照我的設置方式工作。 我需要多個 forms 來為每個產品項目提供更新和刪除選項。 我遇到的問題是,只要我在表單中添加 [formGroup]="profileForm" 指令,表單控件就會停止工作。 我很難讓反應形式工作,因為我的每個 forms 都在表格行中。 在此處輸入圖像描述

不幸的是,我在本地服務器上有數據,因此代碼看起來不像顯示的圖片,但如果您想仔細查看我的代碼,這里是堆棧閃電戰: https://stackblitz.com/github/RashellSmith/Dashboard -前端

更新產品 ts

import { Component, OnInit } from '@angular/core';
import { Product } from '../model/Product';
import { Category } from '../model/Availability';
import { Supplier } from '../model/Supplier';
import { Home } from '../model/Home';
import { HomeService } from '../service/Home.service';
import { SupplierService } from '../service/Supplier.service';
import { CategoryService } from '../service/Category.service';
import { FormGroup, FormControl } from '@angular/forms'
@Component({
  selector: 'app-update-product',
  templateUrl: './update-product.component.html',
  styleUrls: ['./update-product.component.scss']
})
export class UpdateProductComponent implements OnInit {
  availability:boolean;
  category:number;
  orderBy: String;
  Ascdesc: String;
  page = 0;
  home: Home[];
  categories: Category[];
  supplier: Supplier[];
  selectedCategory: Category;
  edit: boolean = false;
  public currentProduct: number;

  toogleEditMode() {
    this.edit = this.edit ? false : true; 
  }

  selectCategory (category) {
       this.category = category.category;
   }

   available(boolean){

    this.availability = boolean;
    }

    update($event){
      this.homeService.getByParm(this.availability,this.category).subscribe(data => {
        this.home = data;
      }); 

    }
    profileForm = new FormGroup({
      id: new FormControl(''),
      name: new FormControl(''),
      category: new FormControl(''),
      fullPrice: new FormControl(''),
      salePrice: new FormControl(''),
      availability: new FormControl(''),
      supplier: new FormControl(''),
      discount: new FormControl(''),

    });

// model = {id: null, productName: '', category: {category: null, categoryName: null}, fullPrice: '', salePrice:'', availability: false, supplier: {supplier:null,supplierName:""},discount:null};
// json = JSON.stringify(this.model);
constructor(private homeService: HomeService,private supplierService: SupplierService,private categoryService: CategoryService) { }

name = new FormControl('');

SortPrice($event:any){
  let icon = document.getElementById("asc-desc1");
  if(icon.className === "fas fa-angle-down"){
    icon.className ="fas fa-angle-up";
    this.homeService.getByPriceAsc().subscribe(data => {
    this.home = data;
  });
  }else{
    icon.className ="fas fa-angle-down"
    this.homeService.getByPriceDesc().subscribe(data => {
      this.home = data;
    });
  };

}
// model = new Newproduct(null,new Category( this.value,"name"),null,null,false,new Supplier(null,null),null);


onSubmit() {
  // TODO: Use EventEmitter with form value
  // console.warn(this.profileForm.value);
}
SortSale($event:any){
  let icon = document.getElementById("asc-desc2");
  if(icon.className === "fas fa-angle-down"){
    icon.className ="fas fa-angle-up";
    this.homeService.getBySaleAsc().subscribe(data => {
    this.home = data;
  });
  }else{
    icon.className ="fas fa-angle-down"
    this.homeService.getBySaleDesc().subscribe(data => {
      this.home = data;
    });
  };

}
SortDiscount($event:any){
  let icon = document.getElementById("asc-desc3");
  if(icon.className === "fas fa-angle-down"){
    icon.className ="fas fa-angle-up";
    this.homeService.getByDiscountAsc().subscribe(data => {
    this.home = data;
  });
  }else{
    icon.className ="fas fa-angle-down"
    this.homeService.getByDiscountDesc().subscribe(data => {
      this.home = data;
    });
  };

}


ngOnInit() {
  this.supplierService.getAll().subscribe(data => {
    this.supplier = data;
  });

    this.homeService.getAll().subscribe(data => {
    this.home = data;
  });
  this.categoryService.getAll().subscribe(data => {
    this.categories = data;
  });

}

}

更新產品 html


  <!-- Table -->
  <form  [formGroup]="profileForm" (ngSubmit)="onSubmit()">
      <p>
          Form Status: {{profileForm.value |json}}
        </p>
  <div class="table-responsive">

    <table  class="table table-bordered table-striped">
      <thead>
      <tr>
        <th>Id</th>
        <th>Product</th>
        <th>Category</th>
        <th>FullPrice <i id ="asc-desc1"class="fas fa-angle-down" (click)="SortPrice($event)"></i></th>
        <th>Saleprice <i id ="asc-desc2"class="fas fa-angle-down" (click)="SortSale($event)"></i> </th>
        <th>Availablity</th>
        <th>Supplier</th>
        <th>Discount<i id ="asc-desc3"class="fas fa-angle-down" (click)="SortDiscount($event)"></i></th>
        <th>Edit</th>
      </tr>
      </thead>
      <tbody>

        <tr  *ngFor="let home of home | paginate:{itemsPerPage:20,currentPage: p} ; index as i">
        <ng-container *ngIf="editMode !== i">
        <td [attr.data-index]="i">{{home.id}}</td>
        <td>{{home.productName}}</td>
        <td>{{home.category.categoryName}}</td>
        <td>{{home.fullPrice}}</td>
        <td>{{home.salePrice}}</td>
        <td>{{home.availability}}</td>
        <td>{{home.supplier.supplierName}}</td>
        <td>{{home.discount }}</td>
      </ng-container>
      <ng-container *ngIf="editMode === i">

          <td><input class="form-control" id="id"  formControlName="id" placeholder={{home.id}}></td>
          <td><input class="form-control" id="name"  formControlName="productName" placeholder={{home.productName}}> Value: {{ profileForm.productName.value }}</td>
          <td><input class="form-control" id="categoryname" [formControl]="category" placeholder={{home.category.categoryName}}></td>
          <td><input class="form-control" id="fullprice"  [formControl]="fullPrice" placeholder={{home.fullPrice}}></td>
          <td><input class="form-control" id="saleprice"   [formControl]="salePrice" placeholder={{home.salePrice}}></td>
          <td><input class="form-control" id="availability"  [formControl]="availability" placeholder={{home.availability}}></td>
          <td>
            <select class="form-control">
              <option *ngFor="let supplier of suppliers">{{supplier.supplierName}}</option>
            </select>
          </td>
          <td><input class="form-control" id="discount" placeholder={{home.discount}}></td>

        </ng-container>


      <!-- if assigned index to editMode matches -->

        <td class="text-right" id="tableDataBtns">
          <div class="btn-group" role="group">
            <button (click)="editMode === i ? editMode = null : editMode = i" data-toggle="modal" data-target="#updateProduct" type="button" class="btn btn-secondary">
              <ng-container *ngIf="editMode === i"><i class="far fa-save"></i></ng-container>
              <ng-container *ngIf="editMode !== i"><i class="far fa-edit"></i></ng-container>
            </button>
            <button type="button" data-toggle="modal" data-target="#deleteProduct" class="btn btn-danger"><i class="far fa-trash-alt"></i></button>
          </div>
        </td>
      </tr>

      <div>
          <select >
            <option *ngFor="let supplier of suppliers" [ngValue]="supplier">{{supplier.supplierName}}</option>
          </select>
        </div>




      </tbody>
    </table>

    <pagination-controls class="myPagination" (pageChange)="p= $event"></pagination-controls>
  </div>
  </form>

您在 HTML 中有一個與formControlName[formControl]的混合。

在您的情況下,您已經在代碼中定義了[formGroup]

所以繼續使用formControlName而不是[formControl]

嗨,您正在使用 reactiveForms,您只需將 [formControl] 更改為 formControlName 對於每個輸入字段,如下所示

<form [formGroup] >
    Your input fields are here.
    <input class="form-control" id="fullprice"  formControlName="fullPrice" placeholder={{home.fullPrice}}></td>

</form>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM