Угловые Реактивные формы Выберите объект по умолчанию - PullRequest
0 голосов
/ 20 февраля 2019

Я использую реактивные формы, и у меня есть поле выбора, которое приходит из массива объектов.Я пытался установить значение по умолчанию, но оно просто не устанавливается.

Моя форма:

<form [formGroup]="markerForm" (ngSubmit)="onSubmit(markerForm)" novalidate>
      <div class="form-group">
        <label for="markerType">{{ 'MARKER.LABEL_TYPE' | translate }}</label>
        <select  class="form-control" formControlName="markerType"   >
           <option id="markerType" [value]="markerType.id" *ngFor="let markerType of markerTypes">{{markerType.desc}}</option>
        </select>
      </div>
</form>

Установить значение по умолчанию:

const test= [{id:1, desc: 'Restaurants'}, {id:2, desc : 'Fire stations'}];
this.markerTypes= test;
console.log(this.markerTypes[1].desc);
this.markerForm.controls['markerType'].setValue( this.markerTypes[1], {onlySelf: true});

Ответы [ 3 ]

0 голосов
/ 20 февраля 2019

Проблема возникла потому, что вы используете markerType.id в качестве значения, но отправляете весь объект this.markerTypes[1] по умолчанию.В этом случае вы должны передать this.markerTypes[1].id.

Если вы хотите использовать объекты в качестве значений, вы должны использовать директиву ngValue для тега опции:

<option id="markerType" [ngValue]="markerType" *ngFor="let markerType of markerTypes">{{markerType.desc}}</option>

Это потому, что в отличие от привязки значения, ngValue поддерживает привязку к объектам

См. рабочий пример здесь

0 голосов
/ 20 февраля 2019

Вы устанавливаете значение по умолчанию как объект:

this.markerForm.controls['markerType'].setValue( this.markerTypes[1], {onlySelf: true});

И вы говорите, что ваше значение является идентификатором:

 <option id="markerType" [value]="markerType.id" *ngFor="let markerType of markerTypes">{{markerType.desc}}</option>

У вас есть несколько вариантов здесь,это зависит от того, как вы хотите, чтобы значение вашей формы было.

Используя Id:

this.markerForm.controls['markerType'].setValue( this.markerTypes[1].id, {onlySelf: true});

<option id="markerType" [value]="markerType.id" *ngFor="let markerType of markerTypes">{{markerType.desc}}</option>

Используя Desc:

this.markerForm.controls['markerType'].setValue( this.markerTypes[1].desc, {onlySelf: true});

<option id="markerType" [value]="markerType.desc" *ngFor="let markerType of markerTypes">{{markerType.desc}}</option>

Использование объекта:

В этом случае вы должны использовать [ngValue], [значение] используется только для строковых переменных типа.

this.markerForm.controls['markerType'].setValue( this.markerTypes[1], {onlySelf: true});

<option id="markerType" [value]="markerType" *ngFor="let markerType of markerTypes">{{markerType.desc}}</option>

Рабочий пример

0 голосов
/ 20 февраля 2019

Попробуйте

проверьте https://stackblitz.com/edit/angular-rqhchz?embed=1

Component.html

<form [formGroup]="markerForm">
   <select id="country" formControlName="markerType">
       <option *ngFor="let c of markerTypes" [ngValue]="c.id">{{ c.desc }} 
      </option>
   </select>
</form>

component.ts

import { FormControl, FormGroup, Validators } from '@angular/forms';

export class Component {

   markerTypes = [{id:1,desc:'abc'}, {id: 2,desc:'xyz'}];
   default= 1;

   markerForm: FormGroup;

   constructor() {
       this.markerForm= new FormGroup({
           markerType: new FormControl(null)
       });
     this.markerForm.controls['markerType'].setValue(this.default, {onlySelf: true});
    }
}

Надеюсь, это поможет

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...