akos.bordas
akos.bordas

Reputation: 199

Is it possible to access selected object from the FormControl value in Angular2?

I'm using reactive forms for validation, so when I want to submit the form I'm using the values from the FormControl instances. My template looks like this:

<select class="form-control" name="status" formControlName="status">
    <option *ngFor="let status of statuses" [ngValue]="status">
        {{status.description}}
    </option>
</select>

Status object looks like this: { id: 1, description: "desc" }

I would like to access to the whole status object with the value property of the FormControl (this.form.controls.status.value), but the selected string is stored in the value not the object.

I can access to the object when I subscribe to the valueChanges event. It seems a little bit illogical. I think I should get the same value when I subscribe to the value changes and when I access to the latest value by the property of the FormControl. It makes no sense to store the latest object in my component by subscribing to the value changes event, because that would force me to duplicate the value. I think this is the purpose of the form control. Maybe I do something wrong !? How can I make it work?

Upvotes: 2

Views: 1280

Answers (1)

alokj03
alokj03

Reputation: 56

My form was working fine in dev, but in prod it failed. If you use Ahead of time compilation (AOT), then form.controls.controlName will fail. You have to use form.get(‘controlName’).

Don’t use control.errors?.someError, use control.hasError(‘someError’)

See this link for more details:

https://github.com/qdouble/angular-webpack2-starter#aot--donts

you can use the following to see the value of your form in your html:

form value: 
{{myForm.value | json}}

Upvotes: 1

Related Questions