提问者:小点点

Angular键值如何使用html插入新键值


这是我使用的类

 export class Product
    {
      id: string;
      title: string;
      description:string;
      numbersOfBuyers2Price: {[key: number]: number};
      category: string;
      img: string;
      endDate: number;
    }

保存新产品的功能

onSaveProduct()
  {
    if (this.form.invalid) {
      return;
    }
    if (this.mode === 'create')
    {
      this.productService.addProduct(
        this.form.value.title,
        this.form.value.description,
        this.form.value.priceArray,
        this.form.value.category,
        this.form.value.img,
        this.form.value.endDate
      );
    }
}

用于创建新产品html

<form [formGroup]="form" (submit)="onSaveProduct()">
  <table class="example-full-width" cellspacing="0"><tr>
    <td>
      <mat-label>Title:</mat-label>
      <input formControlName="title" matInput>
   </td>
    <td>
      <mat-label>Category:</mat-label>
      <input matInput formControlName ="category">
    </td>
    <td>
      <mat-label>IMG:</mat-label>
      <input matInput formControlName ="img">
    </td>
    <td>
      <mat-label>End Date:</mat-label>
      <input matInput formControlName ="endDate">
    </td>
  </tr></table>
  <button mat-raised-button color="accent" type="submit">Save product</button>
</form>

我试图使用html组件为numbersOfBuyers2Price添加多个键值,我只发现如何用*ngfor显示它们


共1个答案

匿名用户

您可以向HTML模板添加UI,以便向组件类的成员添加新的键值对。 然后,当表单提交时,您可以在onSaveProduct函数中使用它。

    <td>
      <mat-label>New Buyers2Price:</mat-label>
      <input matInput [formControl]="newKey">
      <input matInput [formControl]="newValue">
      <button (click)="addKeyValue()">Add</button>
    </td>
class YourComponent {
  private buyer2price: {[key: number]: nuber} = {};
  public newKey = new FormControl('');
  public newValue = new FormControl('');

  public function addKeyValue() {
    this.buyer2price[this.newKey.value] = this.newValue.value;
  }