简体   繁体   中英

Angular 2 Form Getting Duplicated?

I'm using Angular 2 RC3. I'm mostly following the documentation here: https://angular.io/docs/ts/latest/guide/forms.html . When I get to "Submit the form with ngSubmit" things start to go poorly. If I add

<form (ngSubmit)="onSubmit()" #heroForm="ngForm">

I get:

EXCEPTION: Error: Uncaught (in promise): Template parse errors:
Reference "#heroForm" is defined several times.  

If I remove the #heroForm attribute and add:

<button type="submit" class="btn btn-default" ...

Then onSubmit() gets called multiple times. There aren't multiple entries for the form in the dom. Why the apparent duplication, what's going on?

Here's a very simplified component that gets the "is defined several times" error:

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

@Component({
    template: '<form #heroForm="ngForm"></form>'
})
export class Server {
}

This component is loaded via

<router-outlet></router-outlet> 

and an entry in an app.routes.ts file. I'm using Router version 3.0.0-alpha.7.

Solution

I was using both the old and the new forms approaches by accident. My main.ts file was doing bootstrap(AppComponent, [provideForms()]) ... in other words I forgot to add in disableDeprecatedForms() . It should have been bootstrap(AppComponent, [ disableDeprecatedForms(), provideForms() ])

You should check if in your form-templates you have #heroForm tag defined only once. The method onSubmit() should be defined in your component class and needs to be linked to the form in use (using ngSubmit).

If you add your components code (including the imported libs) will be easier to figure out from where you get that error.

But, I suspect you try to use the old forms mechanism. I would suggest you try to use the new approach as is quite different. Unfortunately the documentation is still work in progress and some of the examples provided are using the old approach.

In Angular2 you have 3 ways to configure forms:

1) template-driven

2) model-driven or reactive approach using low level APIs

3) model-driven but with a higher level API (FormBuilder)

Here are 2 very useful blog-posts for this:

I had the same issue, but unlike the first poster I was calling disableDeprecatedForms() . Since I was converting an existing old form, in my case, my component.ts file had the old

import {FORM_DIRECTIVES} from '@angular/common';

and...

directives: [FORM_DIRECTIVES]

Replacing these with the NgForm fixed my issue.

您可以使用(submit)代替(ngSubmit)

尝试了所有方法,唯一对我有用的方法是将<button>更改为<input type="submit">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM