首页 > 解决方案 > 传递数据以形成控制角度

问题描述

我有一个带有 2 个控件的表单组

this.firstFormGroup = this._formBuilder.group({
  name: [''],
  description: [''],
});

我使用 *ngFor 遍历具有这两个属性(名称和描述)的对象数组(我的数据库)

<form [formGroup]="firstFormGroup">
    <ng-template matStepLabel>Choose a bike</ng-template>
    <mat-form-field appearance="fill">
      <mat-label>Choose a bike</mat-label>

      <mat-select formControlName="name" required>
        <mat-option *ngFor="let bike of bikes" [value]="bike.name">
          {{ bike.name }}</mat-option
        >
      </mat-select>
    </mat-form-field>
  </form>

D B:

    export const BIKES: Bike[] = [
  {
    id: 1,
    imgUrl:
      'https://cyclingmagazine.ca/wp-content/uploads/2018/10/Krypton_A18_2016_red_ultegra_16_1.jpg',
    price: 28000,
    discount: 71,
    main: true,
    shop: 'Canada Bike',
    name: 'Argon 18',
    description:
      'Founded by retired cyclist Gervais Rioux in Montreal in 1989, Argon 18 has grown to distribute bikes aross the world and sponsors a number of professional cycling teams and triathletes. In 2019, Argo 18 sponsores Hugo Houle’s U  CI WorldTour team Astana',
    shipping: 'Free shipping',
    discountUntil: '2021-06-02T10:00:00',
    new: true,
    color: ['Blue', 'Grey', 'Orange', 'Black'],
    size: ['S', 'L', 'XL', 'XXL'],
    review: [
      {
        author: 'Michel Delap',
        text: 'Good one, but I have some problem with wheels',
        rating: 4,
      },
    ],
  },

我想将所选自行车的描述属性传递给描述表单控件。

我试图将 description 属性作为具有 formControlName="description" 的隐藏输入的值,但它不起作用

标签: angularangular-materialangular-reactive-formsangular-forms

解决方案


Add change event in your html

<mat-select formControlName="name" required (change)="assignDescription($event)" >
   <mat-option *ngFor="let bike of bikes" [value]="bike.name">
     {{ bike.name }}</mat-option>
</mat-select>

in your .ts

assignDescription(event: any) {
  const bikeName = this.firstFormGroup.name.value;
  
  if (this.firstFormGroup.name.value) {
    const selectedBike = this.bikes.filter((bike) => bike.name === bikeName);
    this.firstFormGroup.description.value = selectedBike.description;
  }
}

推荐阅读