【问题标题】:Pass data to form control angular传递数据以形成控制角度
【发布时间】:2021-01-10 15:36:50
【问题描述】:

我有一个带有 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>

数据库:

    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" 的隐藏输入的值,但它不起作用

【问题讨论】:

  • 你可以将bike对象绑定到mat-select [value]="bike"

标签: angular angular-material angular-reactive-forms angular-forms


【解决方案1】:

在您的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>

在你的.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;
  }
}

【讨论】:

    猜你喜欢
    • 2016-06-08
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-02
    • 2015-09-16
    相关资源
    最近更新 更多