在模板

时间:2018-08-01 13:16:42

标签: angular angular-material

如何从模板中将初始值传递给Mat-select。

此代码段位于ngFor内,因此我无法设置组件的值,只能设置模板的值!

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

console.log始终将obj2显示为null,因此我认为在select上未正确设置该值

谢谢您的帮助!

2 个答案:

答案 0 :(得分:1)

您不应该使用FormControl并使用value进行初始化(完成操作)或进行绑定。要初始化选择值,请在FormControl上进行设置:

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

TS:

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

答案 1 :(得分:0)

根据@ g-tranter的提示,这就是我用作解决方案的内容

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