单击按钮时将变量从模板传递到Angular中的ts文件

问题描述 投票:0回答:1

我有一个具有getter函数的组件,该组件使用forEach遍历对象。在我的html文件中,我能够轻松访问这些变量。我遇到的麻烦是当我想使用按钮来触发另一个函数时,我需要传递一个变量。尽管我可以访问此变量,但是当我尝试在click函数中传递该变量时,该变量仍未定义。我对此很陌生,如果问题措辞不明确,请原谅我。

这是我的代码:我的service1文件中的函数

 viewCompanyIngredients(companyId: number): Observable<Ingredient[]> {
    return this.http.get<Ingredient[]>(`${this.baseUrl}viewCompanyIngredients/${companyId}`, this.httpOptions);
  }

我的service2文件中的函数

 addIngredientsToProduct(productId: number, ingredientId: number)  : Observable<Product[]> {
    const body = `ingredient_id=${ingredientId}`;
    return this.http.post<Product[]>(`${this.baseUrl}addIngredientsToProduct/${productId}`, body, this.httpOptions);
  }

我的ts文件

import {Component, Inject, OnInit} from '@angular/core';
import {MatDialogRef, MAT_DIALOG_DATA} from "@angular/material";
import {ProductService} from "../../../../models/services/product.service";
import {Ingredient} from "../../../../models/ingredient";
import {IngredientService} from "../../../../models/services/ingredient.service";



@Component({
  selector: 'app-contact-add-ingredients-to-products',
  templateUrl: './contact-add-ingredients-to-products.component.html',
  styleUrls: ['./contact-add-ingredients-to-products.component.scss']
})
export class ContactAddIngredientsToProductsComponent implements OnInit {
  productId: number;
  ingredientId: number;
  ingredients: Ingredient[];

  displayIngredientColumns: string[] = ['ingredientName', 'ingredientEvalStatus', 'ingredientEvalDate', 'vendorName', 'addThisIngredient'];


  constructor(public dialogRef: MatDialogRef<ContactAddIngredientsToProductsComponent>,
              @Inject(MAT_DIALOG_DATA) data,
              private productService: ProductService, private ingredientService: IngredientService) {

              this.productId = data.productId;
  }

  ngOnInit() {
    this.viewCompanyIngredients();
  }

  addIngredientsToProduct(productId, ingredientId) {
    console.log(this.ingredientId)
    this.productService.addIngredientsToProduct(this.productId, this.ingredientId).subscribe((res) => {
      console.log(res);

    })
}


  viewCompanyIngredients(): void {
    this.ingredientService.
    viewCompanyIngredients(0).subscribe(
      (res) => {
        if (res[0]) {
          this.ingredients = [];
          res.forEach((item) => {
            item = new Ingredient(item);
            this.ingredients.push(item);
          });
        } else {
          console.warn(res);
        }
        console.log(this.ingredients);
      }
    );
  }

  closeDialog() {
    this.dialogRef.close();
  }



}

我的html文件

<button mat-stroked-button color="secondary" [ngStyle]="{'margin':'1rem 2rem'}" (click)="closeDialog()">Back</button>


<div  *ngIf="ingredients" class="table">
  <h3 matColumnDef="title">Ingredients</h3>
  <table mat-table [dataSource]="ingredients"  class="mat-elevation-z8">
    <ng-container matColumnDef="ingredientName">
      <th mat-header-cell *matHeaderCellDef> Name </th>
      <td mat-cell *matCellDef="let ingredient"> {{ingredient.ingredientName}} </td>
    </ng-container>
    <ng-container matColumnDef="ingredientEvalStatus">
      <th mat-header-cell *matHeaderCellDef> Status </th>
      <td mat-cell *matCellDef="let ingredient"><div *ngIf="ingredient.ingredientEvalStatus == 1">&#10004;</div><div *ngIf="ingredient.ingredientEvalStatus == 0">&#10008;</div></td>
    </ng-container>
    <ng-container matColumnDef="ingredientEvalDate">
      <th mat-header-cell *matHeaderCellDef>Last evaluated</th>
      <td mat-cell *matCellDef="let ingredient"> {{ingredient.ingredientEvalDate}} </td>
    </ng-container>
    <ng-container matColumnDef="vendorName">
      <th mat-header-cell *matHeaderCellDef> Vendor </th>
      <td mat-cell *matCellDef="let ingredient"> {{ingredient.vendorName}} </td>
    </ng-container>
    <ng-container matColumnDef="ingredientNote">
      <th mat-header-cell *matHeaderCellDef>Comment</th>
      <td mat-cell *matCellDef="let ingredient"> {{ingredient.ingredientNote}} </td>
    </ng-container>
    <ng-container matColumnDef="addThisIngredient">
      <th mat-header-cell *matHeaderCellDef> Add This Ingredient </th>
      <td mat-cell *matCellDef="let ingredient">

        <button mat-stroked-button
                (click)="addIngredientsToProduct(productId, ingredient.ingredientId)">Add This Ingredient</button>
      </td>
     </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayIngredientColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayIngredientColumns;"
        [ngClass]="{'green': row.ingredientEvalStatus==1, 'red': row.ingredientEvalStatus==0}"></tr>
  </table>
</div>
<div *ngIf="!ingredients">
  <h1>This company has no ingredients!</h1>
</div>




您会注意到我从另一个组件传入了一个变量,并将其传入了click函数。这可行。如果我传递的是实际数字而不是this.ingredientId,则函数addIngredientstoProduct也将起作用。如何单击模板,从模板访问Ingredient.id,并将其传递给addIngredientsToProduct函数。我尝试了很多事情,但似乎没有任何效果。

angular button binding click
1个回答
0
投票
addIngredientsToProduct(productId, ingredientId) { // ADD THIS LINE this.ingredientId = ingredientId; console.log(this.ingredientId); this.productService.addIngredientsToProduct(this.productId, this.ingredientId).subscribe((res) => { console.log(res); })
© www.soinside.com 2019 - 2024. All rights reserved.