kay
kay

Reputation: 1429

Angular 2 rc4: can not get the value from form

Here is a part of my code.

<form (ngSubmit)="onSubmit(f)" #f="ngForm">
            <label for="city">City</label>
            <input ngControl="cityName" type="text" id="city">
            <button type="submit">Add City</button>
</form>
export class SearchCity {
   onSubmit(form: ControlGroup){
         console.log(form.value.cityName);
   }

It shows Undefined, how can I get the value of cityName?

Upvotes: 0

Views: 203

Answers (1)

micronyks
micronyks

Reputation: 55443

You have to add #cityName="ngForm" in order to get cityName value as shown below.

https://plnkr.co/edit/CvNwKb8lZtIZHcg05lgS?p=preview

<form (ngSubmit)="onSubmit(f.value)" #f="ngForm">  
                <label for="city">City</label>
                <input ngControl="cityName" #cityName="ngForm" type="text" id="city">  
                //added #cityName="ngForm" as you are dealing with ngControl

                <button type="submit">Add City</button>
</form>


onSubmit(myForm){
   console.log(myForm.cityName);
}

Upvotes: 1

Related Questions