角度|使用setValue更改md-select选项

时间:2017-09-25 02:12:35

标签: javascript angular

我试图设置一个选择选项,但似乎无法让它正常工作。运行this.eventForm.controls.venue.setValue(event.venue.name);会将venue的值更改为event.venue.name,但select选项不会更改。

component.ts

const eventObject = this.db.object(`/events/${eventId}`);
    console.log(eventObject);

    this.existingEvent = eventObject
      .takeUntil(this.ngUnsubscribe)
      .subscribe((event: Object) => this.reForm(event),
      (error: any) => { console.log(error) }
      );

  reForm(event): void {

    if (this.eventForm) {
      this.eventForm.reset();
    }

    console.log(this.eventForm.controls.venue);

    this.eventForm.controls.venue.setValue(event.venue.name);

    this.eventForm.patchValue({
      category: event.category,
      date: event.date,
      // venue: event.venue.name,
      description: event.description,
      name: event.name,
    })
  }

component.html

<form [formGroup]="eventForm">

    <md-select class="example-full-width" [ngModelOptions]="{standalone: true}" placeholder="Venue"
                (change)="venueProcess($event)">
                <md-option *ngFor="let venue of venues | async" [value]="venue.$key">
                  {{ venue.name }}
                </md-option>
              </md-select>
</form>

***编辑。设定值后的图像

enter image description here

2 个答案:

答案 0 :(得分:0)

您必须在select选项中添加ngModel, 所以我希望下面的内容适合你(仅限HTML)

<form [formGroup]="eventForm">

<md-select class="example-full-width" [ngModelOptions]="{standalone: true}" placeholder="Venue" [(ngModel)]="event.venue.name"
            (change)="venueProcess($event)">
            <md-option *ngFor="let venue of venues | async" [value]="venue.$key">
              {{ venue.name }}
            </md-option>
          </md-select>

答案 1 :(得分:0)

尝试

this.eventForm.controls.venue.setValue(event.venue.$key);

在HTML模板中,添加formControlName以绑定所有内容:

<md-select formControlName="venue" class="example-full-width" [ngModelOptions]="{standalone: true}" placeholder="Venue" (change)="venueProcess($event)">
   <md-option *ngFor="let venue of venues | async" [value]="venue.$key">
      {{ venue.name }}
   </md-option>
</md-select>

您使用venue.name作为显示文字,venue.$key作为选项值。您应该将表单控件值设置为与选项值匹配,而不是选项显示文本。