【问题标题】:Passing variable from template to ts file in Angular when clicking button单击按钮时将变量从模板传递到Angular中的ts文件
【发布时间】:2020-04-16 08:08:56
【问题描述】:

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

这是我的代码: 我的 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 也可以工作。如何从模板中访问成分 ID,并在单击按钮时将其传递到函数 addIngredientsToProduct 中。我已经尝试了很多东西,但似乎没有任何效果。

【问题讨论】:

  • 您能否在Stackblitz 中重现您的问题?我真的看不出你的问题出在哪里。
  • 我认为您正在将成分.ingredientId 作为参数传递,但该组件没有名为成分的属性。

标签: angular button binding click


【解决方案1】:

您应该将点击事件处理程序的参数分配给this.ingredientId,然后才检查其值并将其传递给服务:

  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);

    })

【讨论】:

    猜你喜欢
    • 2017-11-17
    • 2014-01-01
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    • 2018-09-07
    • 2021-06-30
    • 1970-01-01
    • 2021-09-22
    相关资源
    最近更新 更多