0

I have a form which has an input. I applied two-way event binding on the input, however, it doesn't work. I have imported the FormsModule in my AppModule and I am not getting any errors.

search.component.html:

<form>
  <h1>{{ query }}</h1>
  <input [(ngModel)]="query">
</form>

search.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.scss']
})
export class SearchComponent {
  public query: string;
  
  constructor() {}
}

It works when I do not include the form tag:

<h1>{{ query }}</h1>
<input [(ngModel)]="query">

But I need to use form for submission. Any ideas what's wrong?

Relevant thread.

1 Answer 1

0

I got the following error later, not sure why it didn't show up earlier:

ERROR Error: If ngModel is used within a form tag, either the name attribute must be set or the form
      control must be defined as 'standalone' in ngModelOptions.

      Example 1: <input [(ngModel)]="person.firstName" name="first">
      Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">
    at Function.missingNameException (forms.js:4716)
    at NgModel._checkName (forms.js:5050)
    at NgModel._checkForErrors (forms.js:5033)
    at NgModel.ngOnChanges (forms.js:4956)
    at NgModel.rememberChangeHistoryAndInvokeOnChangesHook (core.js:2197)
    at callHook (core.js:3109)
    at callHooks (core.js:3075)
    at executeInitAndCheckHooks (core.js:3027)
    at refreshView (core.js:7333)
    at refreshComponent (core.js:8465)

As suggested, I resolved it by adding [ngModelOptions]="{standalone: true}":

<form>
  <h1>{{ query }}</h1>
  <input [(ngModel)]="query" [ngModelOptions]="{standalone: true}">
</form>

You could also choose the second route as specified, i.e., add a name attribute and put anything:

<form>
  <h1>{{ query }}</h1>
  <input [(ngModel)]="query" name="something">
</form>
Sign up to request clarification or add additional context in comments.

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.