RaulGM
RaulGM

Reputation: 342

How to get data from a select>option with ngValue

As I said in the title, I can't get any values returned from a form, more specifically a select>option input.

I have seen other questions like this, but they are out of date and most of them say that it was a bug. So I'm verifying if it is still a bug and how is it possible to achieve this now.

I have an object returned from Firebase:

car: {
  {id: 1, name: 'a'},
  {id: 2, name: 'b'},
  {id: 3, name: 'c'}
}

This is the HTML code I expected to work:

<select #id class = "form-control">
   <option *ngFor = "let car of cars" [ngValue] = "car.key">{{ car.name }}</option>
</select>

And resolve in my component:

ngOnInit () {
  this.myForm = this.fb.group({ 
    id: ['', Validators.required]
  });
}

So if I'd console.log the value of the id, this should return the Id of the selected object, but it returns an empty string.

Upvotes: 1

Views: 2602

Answers (3)

dev_in_progress
dev_in_progress

Reputation: 2494

You need to bind it with object

<form #f="ngForm" (submit)="onSubmit()">
    <label>Name</label>
    <div>
        <input [(ngModel)]="user.name" name="user"/>
    </div>
    <label>Service</label>
    <select name="service" [(ngModel)]="user.service">
        <option *ngFor='let service of services' [ngValue]='service'>{{service.name}}</option>
    </select>
    <button type="submit">Create User</button>
</form>

I can see you are using Model driven forms, you don't realy need that if you aint gona do unit testing:

Reference

Here is quick way of defining template driven forms:

User object:

import { Service } from './service';
export User{
   name: string,
   service: Service
}

User Component:

export class UserComponent  implements OnInit{
    user = User;
    services = [{...},{...}];
    ngOnInit() {
        this.user = <User>{}; // Initialize empty object, type assertion, with this we loose type safety
    }
    onSubmit(){
        console.log(this.user); 
    }
}

Upvotes: 1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658135

I think instead of #id you need name="id"

<select name="id" class = "form-control">

for formbuilder to be able to make the connection.

Upvotes: 0

SpareWalrus
SpareWalrus

Reputation: 156

I believe you would need to add a form control to your select field. Would look like:

<select [formControl]="id" class="form-control">

The template reference variable will let you access that DOM element from your Component, but won't work for forms.

I'd recommend reading http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2/ for more information.

Edit: I noticed you've got the form builder group in ngOnInit. Unless you need the formBuilder within ngOnInit, I'd recommend moving it to your constructor.

Upvotes: 0

Related Questions