如何在 Angular 中访问 formControl 的 object 属性?

How to access object property of a formControl in Angular?

我有一个 Angular 具有 object 数组的 FormControl。 一个 object 看起来像:

{id: 'id', title: 'title'} 

我在一个 formGroup 中有一个 formControl 和其他 formControl。

fc= null;    
this.fc= new FormControl(this.array);
this.form = this.formBuilder.group({
      fc: this.fc,
      ...
    });

现在我的 html 中有一个垫子 select:

 <mat-select formControlName="fc" placeholder="Test" multiple>
                <mat-option *ngFor="let op of test" [value]="op.title">{{ op.title }}</mat-option>
              </mat-select>

我怎么能说 formControl 应该使用 object 的标题 属性 来显示数组中的初始值?如果我只将数组映射到标题 属性 一切正常。

 this.fc= new FormControl(this.array.map(x=>x.title));

但我需要整个 object 在我的表格中。

试一试:

import { Component } from '@angular/core';
import { FormGroup, FormBuilder, FormControl } from '@angular/forms';

/** @title Select with multiple selection */
@Component({
  selector: 'select-multiple-example',
  templateUrl: 'select-multiple-example.html',
  styleUrls: ['select-multiple-example.css'],
})
export class SelectMultipleExample {
  test = [
    { id: '1', title: 'Title 1' },
    { id: '2', title: 'Title 2' },
    { id: '3', title: 'Title 3' },
    { id: '4', title: 'Title 4' },
    { id: '5', title: 'Title 5' },
  ];
  form: FormGroup;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.form = this.formBuilder.group({
      fc: [['2', '4']],
    });
  }
}


/**  Copyright 2019 Google Inc. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at http://angular.io/license */

在您的模板中:

<form [formGroup]="form">
  <mat-form-field>
    <mat-label>Toppings</mat-label>
    <mat-select formControlName="fc" multiple>
      <mat-option *ngFor="let item of test" [value]="item.id">{{item.title}}</mat-option>
    </mat-select>
  </mat-form-field>
</form>


<!-- Copyright 2019 Google Inc. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at http://angular.io/license -->

Here's a Working Sample StackBlitz for your ref.

如果你的mat-option像

<mat-option *ngFor="let item of test" [value]="item.id">{{item.title}}</mat-option>

你的 formControl 必须是,e,g - 看那是一个数组或字符串 -

fc: [['2','4']]

如果你的mat-option像

<mat-option *ngFor="let item of test" [value]="item">{{item.title}}</mat-option>

您的 formControl 必须是,例如,-看到它是一个对象数组-,在这种情况下,您需要使用对象的引用

fc: [this.test[1],this.test[3]] //<--use reference to the object

//be careful!!
//fc:[{id:'2',title:'Title2'},{id:'4',title:'Title 4'}] //<--ERROR