[angular] Angular2 Error: There is no directive with "exportAs" set to "ngForm"

i'm on the RC4 and i'm getting the error There is no directive with "exportAs" set to "ngForm" because of my template :

<div class="form-group">
        <label for="actionType">Action Type</label>
        <select
            ngControl="actionType" 
      ===>  #actionType="ngForm" 
            id="actionType" 
            class="form-control" 
            required>
            <option value=""></option>
            <option *ngFor="let actionType of actionTypes" value="{{ actionType.label }}">
                {{ actionType.label }}
            </option>
        </select> 
    </div>

the boot.ts :

import {disableDeprecatedForms, provideForms} from '@angular/forms'; 

 import {bootstrap} from '@angular/platform-browser-dynamic';
 import {HTTP_PROVIDERS, Http} from '@angular/http';
 import {provideRouter} from '@angular/router';

import {APP_ROUTER_PROVIDER} from './routes';

import {AppComponent} from './app.component';

bootstrap(AppComponent, [ disableDeprecatedForms(), provideForms(), APP_ROUTER_PROVIDER, HTTP_PROVIDERS]);

/// so here is my DropdownList :

<fieldset ngControlGroup="linkedProcess" >
                     <div ngControlGroup="Process" >
                         <label>Linked Process</label>
                          <div class="form-group">       
        <select 
            ngModel
            name="label" 
            #label="ngModel" 
            id="label" 
            class="form-control" required
            (change)="reloadProcesse(list.value)" 
            #list>
            <option value=""></option>
            <!--<option value=`{{ActionFormComponent.getFromString('GET'')}}`></option>-->                 
            <option *ngFor="let processus of linkedProcess?.processList?.list; let i = index" 
            value="{{ processus[i].Process.label}}">
                {{processus.Process.label}}
            </option>
        </select> 
        </div>
     </div>

//my component ts :

i was representing it in the old forms like this :

 categoryControlGroups:ControlGroup[] = [];
     categories:ControlArray = new ControlArray(this.categoryControlGroups);

and now i'm doing this :

categoryControlGroups:FormGroup[] = [];
     categories:FormArray = new FormArray(this.categoryControlGroups);

you think it's the cause of the prob ??

This question is related to angular typescript angular2-forms

The answer is


if ngModule is not working in input means try...remove double quotes around ngModule

like

<input #form="ngModel" [(ngModel)]......></input>

instead of above

<input #form=ngModel [(ngModel)]......></input> try this

I had this problem and I realized I had not bound my component to a variable.

Changed

<input #myComponent="ngModel" />

to

<input #myComponent="ngModel" [(ngModel)]="myvar" />


In my case I had to add FormsModule and ReactiveFormsModule to the shared.module.ts too:

(thanks to @Undrium for the code example):

import { NgModule }                                 from '@angular/core';
import { CommonModule }                             from '@angular/common';
import { FormsModule, ReactiveFormsModule }         from '@angular/forms';

@NgModule({
  imports:      [
    CommonModule,
    ReactiveFormsModule
  ],
  declarations: [],
  exports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ]
})
export class SharedModule { }

I faced the same issue. I had missed the forms module import tag in the app.module.ts

import { FormsModule } from '@angular/forms';

@NgModule({
    imports: [BrowserModule,
        FormsModule
    ],

I had this problem because I had a typo in my template near [(ngModel)]]. Extra bracket. Example:

<input id="descr" name="descr" type="text" required class="form-control width-half"
      [ngClass]="{'is-invalid': descr.dirty && !descr.valid}" maxlength="16" [(ngModel)]]="category.descr"
      [disabled]="isDescrReadOnly" #descr="ngModel">

I had the same problem which was resolved by adding the FormsModule to the .spec.ts:

import { FormsModule } from '@angular/forms';

and then adding the import to beforeEach:

beforeEach(async(() => {
  TestBed.configureTestingModule({
    imports: [ FormsModule ],
    declarations: [ YourComponent ]
  })
.compileComponents();
}));

Also realized this problem comes up when trying to combine reactive form and template form approaches. I had #name="ngModel" and [formControl]="name" on the same element. Removing either one fixed the issue. Also not that if you use #name=ngModel you should also have a property such as this [(ngModel)]="name" , otherwise, You will still get the errors. This applies to angular 6, 7 and 8 too.


If you are getting this instead:

Error: Template parse errors:

There is no directive with "exportAs" set to "ngModel"

Which was reported as a bug in github, then likely it is not a bug since you might:

  1. have a syntax error (e.g. an extra bracket: [(ngModel)]]=), OR
  2. be mixing Reactive forms directives, such as formControlName, with the ngModel directive. This "has been deprecated in Angular v6 and will be removed in Angular v7", since this mixes both form strategies, making it:
  • seem like the actual ngModel directive is being used, but in fact it's an input/output property named ngModel on the reactive form directive that simply approximates (some of) its behavior. Specifically, it allows getting/setting the value and intercepting value events. However, some of ngModel's other features - like delaying updates withngModelOptions or exporting the directive - simply don't work (...)

  • this pattern mixes template-driven and reactive forms strategies, which we generally don't recommend because it doesn't take advantage of the full benefits of either strategy. (...)

  • To update your code before v7, you'll want to decide whether to stick with reactive form directives (and get/set values using reactive forms patterns) or switch over to template-driven directives.

When you have an input like this:

<input formControlName="first" [(ngModel)]="value">

It will show a warning about mixed form strategies in the browser's console:

It looks like you're using ngModel on the same form field as formControlName.

However, if you add the ngModel as a value in a reference variable, example:

<input formControlName="first" #firstIn="ngModel" [(ngModel)]="value">

The error above is then triggered and no warning about strategy mixing is shown.


The correct way of use forms now in Angular2 is:

<form  (ngSubmit)="onSubmit()">

        <label>Username:</label>
        <input type="text" class="form-control"   [(ngModel)]="user.username" name="username" #username="ngModel" required />

        <label>Contraseña:</label>
        <input type="password" class="form-control"  [(ngModel)]="user.password" name="password" #password="ngModel" required />


    <input type="submit" value="Entrar" class="btn btn-primary"/>

</form>

The old way doesn't works anymore


Check that you have both ngModel and name attributes in your select. Also Select is a form component and not the entire form so more logical declaration of local reference will be:-

<div class="form-group">
    <label for="actionType">Action Type</label>
    <select
            ngControl="actionType" 
      ===>  #actionType="ngModel"
            ngModel    // You can go with 1 or 2 way binding as well
            name="actionType"
            id="actionType" 
            class="form-control" 
            required>
            <option value=""></option>
            <option *ngFor="let actionType of actionTypes" value="{{ actionType.label }}">
                {{ actionType.label }}
            </option>
        </select> 
    </div>

One more Important thing is make sure you import either FormsModule in the case of template driven approach or ReactiveFormsModule in the case of Reactive approach. Or you can import both which is also totally fine.


Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to angular2-forms

How can I manually set an Angular form field as invalid? Angular 2 Cannot find control with unspecified name attribute on formArrays Remove all items from a FormArray in Angular Angular ReactiveForms: Producing an array of checkbox values? How to make readonly all inputs in some div in Angular2? tslint / codelyzer / ng lint error: "for (... in ...) statements must be filtered with an if statement" Min / Max Validator in Angular 2 Final TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm" Can't bind to 'formGroup' since it isn't a known property of 'form' ngModel cannot be used to register form controls with a parent formGroup directive