簡體   English   中英

默認 Select 選項 Angular 8 反應式 forms

[英]Default Select option Angular 8 Reactive forms

我想從我的 API 中獲取我的所有數據,並將它們設置為我的反應形式的默認值。 我能夠使用ngModel綁定所有值。 我只是不知道如何用我的select做到這一點。 在我的 HTML 中,我從我的家庭服務中獲得了我的第一個 select 選項。 第二個選項,我正在使用我的類別服務來顯示所有類別。 我這樣做是為了能夠根據我當前選擇的產品設置默認值。 我遇到的主要問題是我想將 ngModel 綁定到第一個選項,這樣默認情況下,如果我要提交我的表單,它將是提交的第一個選項。 我見過人們使用補丁值來執行此操作,但我的問題是我不知道如何處理通過 html 獲得的數據,因為它顯示在 html 中而不是 ts 文件中。 使用ngModel是我能想到的最好的解決方案。

html

  <!-- Table -->
  <form  [formGroup]="updateProduct" >
      <p>
          Form Status: {{updateProduct.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>{{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" [(ngModel)]="home.id" disabled></td>
          <td><input class="form-control" id="productName"  formControlName="productName" [(ngModel)]="home.productName"></td>
          <td>
              <select class="form-control" formControlName="category" >
                <option selected="selcected"  class="opt1" >{{home.category.categoryName}}</option>
                <option *ngFor="let category of categories">{{category.categoryName}}</option>
              </select>
            </td>
          <td><input class="form-control" id="fullprice" formControlName="fullPrice" [(ngModel)]="home.fullPrice"></td>
          <td><input class="form-control" id="saleprice"   formControlName="salePrice" [(ngModel)]="home.salePrice"></td>
          <td><input type="checkbox" class="form-control" id="availability"  formControlName="availability" [(ngModel)]="home.availability"></td>
          <td>
            <select class="form-control" formControlName="supplier">
              <option selected="selcected" class="opt1">{{home.supplier.supplierName}}</option>
              <option *ngFor="let supplier of suppliers">{{supplier.supplierName}}</option>
            </select>
          </td>
          <td><input class="form-control" id="discount" formControlName="discount"[(ngModel)]="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>
      </tbody>
    </table>

    <pagination-controls class="myPagination" (pageChange)="p= $event"></pagination-controls>
  </div>
  </form>
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[];
  suppliers: 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;
      }); 
  
    }
    updateProduct = new FormGroup({
      id: new FormControl(''),
      productName: 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) { }
 

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.suppliers = data;
  });
  
    this.homeService.getAll().subscribe(data => {
    this.home = data;
  });
  this.categoryService.getAll().subscribe(data => {
    this.categories = data;
  });
  
}

}

圖片

不要混淆模板驅動的響應式 Forms。 你可以在這里閱讀更多信息。

當您在同一個視圖中使用 3 個 API 時,您可以等待它們全部響應,然后執行您想要的邏輯。 這可以通過將 observables 設置為 object(rxjs < 6.5 的數組)並使用forkJoin 來完成

const observables = {
  suppliers: this.supplierService.getAll(),
  home: this.homeService.getAll(),
  categories: this.categoryService.getAll()
};

forkJoin(observables).subscribe({ suppliers, home, categories } => {
  this.suppliers = suppliers;
  this.home = home;
  this.categories = categories;
});

之后,使用 patchValue 更新表單:

updateProfile() {
  this.updateProduct.patchValue({
    id: this.home.id,
    productName: this.home.productName,
    category: this.home.category,
    fullPrice: this.home.fullPrice,
    salePrice: this.home.salePrice,
    availability: this.home.availability,
    supplier: this.home.supplier,
    discount: this.home.discount
  });
}

最后一件事,刪除selected的選項並為選項添加一個值,以便在修補值后可以 select 它(最好有一個類別的 ID 將它們設置為值)

<select class="form-control" formControlName="category" >
  <option [value]="home.category.categoryName" class="opt1" >{{home.category.categoryName}}</option>
  <option [value]="category.categoryName" *ngFor="let category of categories">{{category.categoryName}}</option>
</select>

現在,當您要提交時,可以通過表單讀取值:

const formValues = this.updateProduct.value;
// This will contains all the values, you can access them by formValues.firstName ...etc

有關反應式 Forms 的更多信息,您可以在此處查看

暫無
暫無

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

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