简体   繁体   中英

Angular2 - set initial value in select - Reactive forms

I have a problem with setting default option in select. I am getting array from server and I want to select second item in array which is documentTypes[1]. Here's my code and what I tried to do.

Select HTML

<select formControlName="type">
    <option *ngFor="let document of documentTypes" [ngValue]="document" [attr.selected]="selectedType">{{document.name | translate}}</option>
</select>

Values from server

getDocumentTypes() {
    this._api.send(urlValues.documentType, 'Get').subscribe(
        res => {
            this.selectedType = res.content.types[1];
            this.documentTypes = res.content.types;
        },
        err => console.log(err)
    );
}

I also have build document method and I tried this

buildDocument(document?: any) {
    if (document) {
        this.documentForm = this._fb.group({
            customer: this._fb.group({
                oib: document.customer.oib,
                location: document.customer.location
            }),
            payment_method: document.payment_method,
            delivery_method: document.delivery_method,
            status: document.status,
            type: document.type,
            expiration_date: document.expiration_date,
            delivery_date: document.delivery_date,
            note: document.note
        });
    } else {
        this.documentForm = this._fb.group({
            customer: this._fb.group({
                oib: null,
                location: null
            }),
            payment_method: null,
            delivery_method: null,
            status: null,
            type: this.documentTypes[1],
            expiration_date: '',
            delivery_date: '',
            note: ''
        });
    }
}

Do you have any other solutions? Thanks

Make use of the formControl instead of having [attr.selected] . Perhaps you also need to use eg patchValue , since data is async and set the preselected value after data has been retrieved, so that your app won't throw an error when trying to build the form if data is not present.

So your select would look something like this:

<select name="document" formControlName="type">
    <option *ngFor="let doc of documentTypes" [value]="doc.name">  
        {{doc.name}}
    </option>
</select>

And when you have received data from the API, you can use patchValue :

  this.documentForm
    .patchValue({
        type: this.documentTypes[1].name
    })

Here's a demo plunker , where Set Value button sort of simulates that data is coming async, just to showcase the patchValue :)

PS:

You can use ngValue if you need to bind the whole object, but that also means that your form value will contain the whole object, similar to this:

{
  "type": {
    "id": 2,
    "name": "Doc 2"
  }
}

and maybe that is not what you want, so I'm using just the name here, so your form value looks like this:

{
  "type": "Doc 3"
}

Try this :

getDocumentTypes() {
    this._api.send(urlValues.documentType, 'Get').subscribe(
        res => {
            this.selectedType = res.content.types[1];
            this.documentTypes = res.content.types;
            this. documentForm.patchValue({'type': res.content.types[1]}, {onlySelf: true}) //Add this line
        },
        err => console.log(err)
    );

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM