1

I am trying to bind ngModel from text input but it's is not working. Here is my code:

Template:

<form (ngSubmit)="onSubmit()">
    <div class="form-group">
        <input type="text" class="form-control" [(ngModel)]="message">
    </div>
    <input type="submit">
</form>

Component:

export class Component implements OnInit {
  message:string

  onSubmit() {
    console.log(this.message);
  }
}

Always getting undefined value. How to bind value from the text input to variable?

2 Answers 2

7

you have to give input a name property when using template-driven form.

<input type="text" name="message" [(ngModel)]="message">

refer this simple plunker demo.

Sign up to request clarification or add additional context in comments.

1 Comment

idk why but I always seem to miss this. also applies for non-input elements as well in case you are using other angular directives or third party inputs.
2

You are missing ngForm

<form #f="ngForm" (ngSubmit)="onSubmit(f)">
      <div class="form-group">
        <input type="text" class="form-control" name="message" [(ngModel)]="message">
      </div>
      <input type="button">
    </form>

export class Component implements OnInit {
  message:string

   ngOnInit() {
this.message = "test";
}

  onSubmit(form: ngForm) {
    console.log(form.value);
  }
}

4 Comments

you're not assigning any value to message
I have the same code as here but message is allways empty object. I noticed that when I open my page with this form (localhost:4200/page/something) url was change to localhost:4200, but when i remove [(ngModel)]="message" url is correct
have you imported the ngForm from angular/forms ?

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.