1

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

6
  • A plunkr would be very useful. Commented Mar 6, 2017 at 8:10
  • That is if(document) { for? Is the 2nd (else) branch event executed? Commented Mar 6, 2017 at 8:10
  • If(document) is for editing form, when I get existing document data and fill the form, I just call buildDocument(document) @GünterZöchbauer Commented Mar 6, 2017 at 8:12
  • I would use an ngModel for the selected value in the select. Commented Mar 6, 2017 at 8:31
  • 1
    You don't need to replicate your code. Just set your form to a empty model. When editing, you populate your empty model as document. Concerning your initial issue, could you show us the method that retrieve data from database ? Commented Mar 6, 2017 at 8:32

2 Answers 2

2

Make use of the formControl instead of having [attr.selected]. Perhaps you also need to use e.g 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"
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.