如何将表单控件值作为对象并在输入字段中呈现其标签?

时间:2019-10-19 23:43:55

标签: angular angular-material

我有一个简单的表格,其中的输入字段具有自动完成功能(角度材料组件)。问题是,当我从自动完成框中选择值时,输入字段会产生[Object object]作为值,而我希望它是某种与估值师相关的文本。可能是开箱即用的,还是我必须直接操作DOM元素才能实现?

该字段的

值故意是Host对象。

表格:

<form [formGroup]="form" class="full-width">
  <mat-form-field>
    <mat-label>Host</mat-label>
    <input type="text" matInput formControlName="host" [matAutocomplete]="hostSuggestionsAutocomplete"
           placeholder="Host"/>
  </mat-form-field>
  <mat-form-field>
    <input matInput formControlName="delay" placeholder="Delay" type="number" min="1" max="3600"/>
    <mat-error>Delay must be between 1 and 3600 seconds</mat-error>
  </mat-form-field>
</form>

<mat-autocomplete #hostSuggestionsAutocomplete=matAutocomplete>
  <mat-option *ngFor="let hostSuggestion of hostSuggestions"
              [value]="hostSuggestion">{{hostSuggestion.toViewLabel()}} #{{hostSuggestion.id}}</mat-option>
</mat-autocomplete>

主机:

export class Host {
  id: number;
  address: String;
  label: String;
  status: HostStatus;
  lastStatusUpdate: Date;
}
Result af

从自动完成功能中进行选择:

enter image description here

我希望它可以代替[Object object]value.id + value.address或类似名称-通常是自定义标签。

在AngularDart中,有一个选项可以指定已重命名的项目-该函数可以获取值并为其生成“标签”,并在输入字段中呈现该标签。

2 个答案:

答案 0 :(得分:0)

我不知道您的确切组件类,但这是一个示例:

export class FormFieldObject {
  options: FormGroup;
  value: Host;

  constructor(formBuilder: FormBuilder) {
    this.value = {id: 123, address: '555 Some Street'};

    this.options = formBuilder.group({
      color: 'primary',
      val: this.value.id + ' ' + this.value.address.toString(),
    });
  }
}

模板:

<form class="example-container" [formGroup]="options" [style.fontSize.px]="20">
  <mat-form-field [color]="options.value.color">
    <mat-label>Host</mat-label>
    <input matInput type="text" placeholder="Host" formControlName="val" min="10">
  </mat-form-field>
</form>

这应该在字段中显示123 555 Some Street

答案 1 :(得分:0)

和往常一样,我知道有一个解决方案,但是由于我没有仔细阅读文档而忘记了解决方案。我需要的是[displayWith]的{​​{1}}属性。这与在有角飞镖组件中渲染的项目完全相同。

https://material.angular.io/components/autocomplete/overview#setting-separate-control-and-display-values