javascript - 使用 Angular 8 响应式表单捕获表单输入

标签 javascript node.js angular typescript ecmascript-6

我想让我的表单按照我设置的方式工作。我需要多个表单来为每个产品项目提供更新和删除选项。我遇到的问题是,一旦我在表单中添加 [formGroup]="profileForm"指令,表单控件就会停止工作。我很难让响应式(Reactive)表格工作,因为我的每个表格都在表格行中。 enter image description here

不幸的是,我在本地服务器上有数据,所以代码看起来不像显示的图片,但如果你想仔细看看我的代码,这里是堆栈 Blitz :https://stackblitz.com/github/RashellSmith/Dashboard-FrontEnd

更新产品 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]

关于javascript - 使用 Angular 8 响应式表单捕获表单输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58653729/

相关文章:

javascript - promise 并修改返回值

javascript - 如何在 Javascript 对象中引用 JSON 集作为键

node.js - cc1.exe : sorry, 未实现:64 位模式未在退出状态 2 退出状态 1 中编译

node.js - Passport-azure-ad,它是否解析并验证 token ?

javascript - 启用/禁用动态 Bootstrap 工具提示

javascript - 使用向上/向下箭头导航 HTML 表单

node.js - Nodeunit 未检测到 did()

angular - 我应该如何在 Angular 4 的组件的 HTML 模板中使用服务中的 BehaviorSubject 类?

javascript - Angular 8 使用 ngIf 和异步管道来显示和隐藏 HTML 元素

javascript - Angular 异步数据