thesystem
thesystem

Reputation: 604

Make a form and fetch values for non-input fields with Angular Material

I have a Angular Material form with a dropdown menu, from which a customer can select a value.

<form>
  <mat-form-field>
    <mat-label>CHOOSE ACCOUNT</mat-label>
    <mat-select>
      <mat-option *ngFor="let account of accounts" [value]="account.name">{{account.name}}</mat-option>
    </mat-select>
  </mat-form-field>
</form>

At the same time, I follow this guide: https://angular.io/start/forms, which guides you to implement formControlName. I want to apply this to <mat-option>, so that I can fetch the chosen value from the dropdown. I have implemented all of the steps in the guide, but it seems like formControlName doesnt work very well with <mat-option>.

So in short: How do I make a dropdown with Angular Material (done above), and be able to fetch the chosen value from a dropdown?

Upvotes: 0

Views: 1002

Answers (3)

Chund
Chund

Reputation: 449

Uncorrect see below for better way

You might simply hook up a [(NgModel)] which links the selects value to the Value of your chosen FormControl, which itself just get created in your .ts-file. Something like:

comp.ts

/.../    
ngOnInit(){
      this.form.registerControl('OptionsControl', this.formbuilder.control());
      this.optionsControl = this.form.get('OptionsControl');
/../

comp.html

<mat-select [(ngModel)]="optionsControl.value">
      <mat-option *ngFor="let account of accounts" [value]="account.name">{{account.name}}</mat-option>
</mat-select>

___EDIT___

The value attribute of a formcontrol is now readonly and can therefore not be directly assigned that way. Instead the selections should be chosen as a listened event like below:

 <mat-select placeholder="Select your choice">
    <mat-option (onSelectionChange)="optionsControl.setValue(account)" *ngFor="let account of accounts"
                [value]="account.name">{{account.name}}
   </mat-option>
  </mat-select>

Thanks to @Adam to mention this solution first, i simply felt the need to correct my mistakes here.

Upvotes: 1

JuNe
JuNe

Reputation: 1997

The formControlName works fine with a mat-select. You have to put the 'formControlName' property in the mat-select and not in the mat-option.

<mat-select formControlName="myFormControl">
  <mat-option *ngFor="let account of accounts" [value]="account.name">{{account.name}</mat-option>
</mat-select>

Upvotes: 2

Alex
Alex

Reputation: 419

You can use (onSelectionChange) to achieve this.

Simply use it on mat-option tag and handle form value change in custom function

component.html

<mat-option 
  *ngFor="let account of accounts"
  [value]="account.name"
  (onSelectionChange)="selected($event)"
>{{account.name}}</mat-option>

component.ts

selected(event) {
 this.myForm.controls.nameOfValueToBeChanged.setValue([event.value]);
 // or do whatever you want with event.value
}

Upvotes: 1

Related Questions