Nicholas Foden
Nicholas Foden

Reputation: 156

Initial value for mat-select from within template

How do you pass an initial value to a mat-select, from within a template.

This snippet is within an ngFor so I cannot set the value from the component, only the template!

  /** Compare two status' to see if they are the same */
  compareStatus(obj1, obj2){
    console.log(obj1, obj2);
    return (obj1 && obj2) ? obj1.status === obj2.status : false;
  }
<mat-form-field>
  <mat-select placeholder="Status"
    [formControl]="statusForm"
    floatLabel="never"
    name="status"
    [value]="{status: booking.status}"
    [compareWith]="compareStatus"
    id="status">
    <mat-option [value]="{ status: null, booking: booking._id }">
	    No Status
    </mat-option>
    <mat-option [value]="{ status: 'checked', booking: booking._id }">
	    Checked In
    </mat-option>
    <mat-option [value]="{ status: 'paid', booking: booking._id }">
	    Paid
    </mat-option>
    <mat-option [value]="{ status: 'ticket', booking: booking._id }">
	    Ticket
    </mat-option>
    <mat-option [value]="{ status: 'voucher', booking: booking._id }">
	    Voucher
    </mat-option>
    <mat-option [value]="{ status: 'dna', booking: booking._id }">
	    Did Not Attend
    </mat-option>
  </mat-select>
</mat-form-field>

the console.log always shows obj2 as null so I don't think the value is being properly set on the select

Thanks for your help in advance!

Upvotes: 0

Views: 733

Answers (2)

Nicholas Foden
Nicholas Foden

Reputation: 156

following the hint from @g-tranter , here is what I used as the solution

<mat-select placeholder="Status"
			floatLabel="never"
			name="status"
			#status
			[value]="{status: booking.status}"
			[compareWith]="compareStatus"
			id="status"
			(selectionChange)="this.saveStatus(status.value)">
		<mat-option [value]="{ status: null, booking: booking._id }">
    		No Status
  	</mat-option>
    <mat-option [value]="{ status: 'checked', booking: booking._id }">
    		Checked In
  	</mat-option>
  	<mat-option [value]="{ status: 'paid', booking: booking._id }">
    		Paid
  	</mat-option>
  	<mat-option [value]="{ status: 'ticket', booking: booking._id }">
    		Ticket
  	</mat-option>
  	<mat-option [value]="{ status: 'voucher', booking: booking._id }">
    		Voucher
  	</mat-option>
  	<mat-option [value]="{ status: 'dna', booking: booking._id }">
    		Did Not Attend
  	</mat-option>
	</mat-select>

Upvotes: 0

G. Tranter
G. Tranter

Reputation: 17918

You shouldn't use a FormControl and use value either to initialize (as you have done) or to bind. To initialize the select value, set in on the FormControl:

<mat-select placeholder="Status"
    [formControl]="statusForm"
    floatLabel="never"
    name="status"
    [compareWith]="compareStatus"
    id="status">

TS:

statusForm = new FormControl({status: booking.status});

Upvotes: 1

Related Questions