Antoniossss
Antoniossss

Reputation: 32507

How to have a form control value as an object and render its label in input field?

I have simple form where I have input field with autocomplete (Angular Material components). The thing is, when I select value from autocomplete box, Input fields yelds [Object object] as value while I would like it to be some sort of valuer related text. Is it possible out of the box or do I have to manipulate DOM element directly to achieve that?

value of that field is an Host object intentionally .

Form:

<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>

Host:

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

ter picking from autocomplete:

enter image description here

Instead of [Object object] I would like it to be lets say value.id + value.address or something similar - in general, custom label for that.

In AngularDart there was an option to specify item redered - a function that takes value and produces "label" for it that is rendered in input field.

Upvotes: 2

Views: 5483

Answers (2)

Antoniossss
Antoniossss

Reputation: 32507

As always, I knew there is a solution but I forgot what it was as I was reading documentation not carefully enought. What I needed is [displayWith] attribute of MatAutocomplete. This is exactly the same thing as item rendered in angular dart components.

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

Upvotes: 5

ulmas
ulmas

Reputation: 2253

I don't know your exact component class, but here is an example:

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(),
    });
  }
}

Template:

<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>

This should show 123 555 Some Street in the field.

Upvotes: 0

Related Questions