Angular 6表单模板错误:“没有将“ exportAs”设置为“ ngForm”的指令”

时间:2018-09-17 17:14:19

标签: angular bootstrap-4

我已经下载了Angular 6 + bootstrap 4免费皮肤-https://startangular.com/product/sb-admin-bootstrap-4-angular-6/ 尝试使用时 我不断收到错误: 没有将“ exportAs”设置为“ ngForm”的指令。

我的app.module.ts:

 import {CommonModule} from '@angular/common';
    import {HTTP_INTERCEPTORS, HttpClient, HttpClientModule, HttpHeaders} from '@angular/common/http';
    import {NgModule} from '@angular/core';
    import {BrowserModule} from '@angular/platform-browser';
    import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
    import {TranslateLoader, TranslateModule} from '@ngx-translate/core';
    import {TranslateHttpLoader} from '@ngx-translate/http-loader';

    import {AppRoutingModule} from './app-routing.module';
    import {AppComponent} from './app.component';
    import {AuthGuard} from './shared';
    import {TokenInterceptor} from './shared/authtoken';
    import {AuthService} from './shared/services/auth/auth.service';
    import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
    import { FormsModule, ReactiveFormsModule } from '@angular/forms';

    // AoT requires an exported function for factories
    export const createTranslateLoader = (http: HttpClient) => {
        return new TranslateHttpLoader(http, './assets/i18n/', '.json');
    };

    @NgModule({
        imports: [
            CommonModule,
            BrowserModule,
            FormsModule,
            ReactiveFormsModule,
            BrowserAnimationsModule,
            HttpClientModule,
            TranslateModule.forRoot({
                loader: {
                    provide: TranslateLoader,
                    useFactory: createTranslateLoader,
                    deps: [HttpClient]
                }
            }),
            AppRoutingModule
        ],
        declarations: [AppComponent],
        providers: [
            AuthGuard,
            {
                provide: HTTP_INTERCEPTORS,
                useClass: TokenInterceptor,
                multi: true
            },
            AuthService
        ],
        exports: [
            CommonModule,
            FormsModule,
            ReactiveFormsModule
        ],
        bootstrap: [AppComponent]
    })
    export class AppModule {
    }

    platformBrowserDynamic().bootstrapModule(AppModule);

我的login.component.ts:

    import {Component, ElementRef, OnInit} from '@angular/core';
    import {Router} from '@angular/router';
    import {routerTransition} from '../router.animations';
    import {HttpClient} from '@angular/common/http';
    import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';

    @Component({
        selector: 'app-login',
        templateUrl: './login.component.html',
        styleUrls: ['./login.component.scss'],
        animations: [routerTransition()]
    })

    export class LoginComponent implements OnInit {

        public myform: FormGroup;
        public username: FormControl;
        public password: FormControl;

        constructor(public router: Router, private httpClient: HttpClient,
        private formBuilder: FormBuilder) {
        }

        ngOnInit() {
            this.myform = this.formBuilder.group({
                username: new FormControl('', [
                    Validators.minLength(4),
                    Validators.required
                ]),
                password: new FormControl('', [
                    Validators.minLength(4),
                    Validators.required
                ])
            });
        }

        async onLoggedin(form: ElementRef) {

            console.log('Start login... ' + form);
        await this.httpClient.post<AuthenticationResponse>('http://127.0.0.1:51120/login',
            {'username': this.username.value, 'password': this.password.value})
            .toPromise().then(
                data => {
                    console.log('Successfully logged in with user name: ', data.name);
                    localStorage.setItem('token', data.token);
                    localStorage.setItem('isLogin', 'true');
                },
                error => {
                    if (!error.ok) {
                        console.log('Error: ' + error.message);
                    } else {
                        console.log('Failed login message: ', error.error.message);
                    }

                    localStorage.removeItem('token');
                    localStorage.removeItem('isLogin');
                    this.router.navigate(['/login']);
                });

        return false;
    }
}

    interface AuthenticationResponse {
        status: string;
        code: string;
        message: string;
        id: number;
        token: string;
        username: string;
        role: string;
        name: string;
        companyName: string;
    }

我的login.component.html:

<div class="login-page" [@routerTransition]>
    <div class="row justify-content-md-center">
        <div class="col-md-4">
            <img src="assets/images/logo.png" width="150px" class="user-avatar" />
            <h1><h1>Fish farms login</h1></h1>
            <form role="form" (ngSubmit)="onLoggedin(f)" #f="ngForm" novalidate>
                <div class="form-content">
                    <div class="form-group">
                        <input type="text" id="username" name="username" class="form-control input-underline input-lg" required minlength="4" 
                   formControlName="username" placeholder="Username" ngModel>
                        <div class="form-group">
                            <input type="password" id="password" name="password" class="form-control input-underline input-lg" required 
                       minlength="4" formControlName="password" placeholder="Password" ngModel>
                        </div>
                    </div>
                    <button type="submit" class="btn rounded-btn" [routerLink]="['/dashboard']">Log in</button>
                    <a class="btn rounded-btn" [routerLink]="['/signup']">Register</a>
                </div>
            </form>
        </div>
    </div>
</div>

到处都有回复,要求添加到@NgModule({     进口:[         表格模块         ReactiveFormsModule,

但这对我根本不起作用。 请指教

1 个答案:

答案 0 :(得分:0)

您的模板有问题

<form role="form" (ngSubmit)="onLoggedin(f)" #f="ngForm" novalidate>

这里您使用的是#f="ngForm",它通常用于模板驱动表单,并且正在TypeScript类中创建反应式表单。

您应该在同一组件中同时使用其中之一,但不能同时使用。

无论如何,您都可以访问组件类中的表单。

onLoggedin可以使用this.myform

直接访问表单

要解决此问题,请从模板中删除#f="ngForm"

<div class="login-page" [@routerTransition]>
  <div class="row justify-content-md-center">
    <div class="col-md-4">
      <img src="assets/images/logo.png" width="150px" class="user-avatar" />
      <h1>
        <h1>Fish farms login</h1>
      </h1>
      <form role="form" (ngSubmit)="onLoggedin()" novalidate>
        <div class="form-content">
          <div class="form-group">
            <input type="text" id="username" name="username" class="form-control input-underline input-lg" required minlength="4" formControlName="username" placeholder="Username" ngModel>
            <div class="form-group">
              <input type="password" id="password" name="password" class="form-control input-underline input-lg" required minlength="4" formControlName="password" placeholder="Password" ngModel>
            </div>
          </div>
          <button type="submit" class="btn rounded-btn" [routerLink]="['/dashboard']">Log in</button>
          <a class="btn rounded-btn" [routerLink]="['/signup']">Register</a>
        </div>
      </form>
    </div>
  </div>
</div>

在您的组件类中:

import {Component, ElementRef, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {routerTransition} from '../router.animations';
import {HttpClient} from '@angular/common/http';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  animations: [routerTransition()]
})

export class LoginComponent implements OnInit {

  public myform: FormGroup;
  public username: FormControl;
  public password: FormControl;

  constructor(public router: Router, private httpClient: HttpClient,
    private formBuilder: FormBuilder) {}

  ngOnInit() {
    this.myform = this.formBuilder.group({
      username: new FormControl('', [
        Validators.minLength(4),
        Validators.required
      ]),
      password: new FormControl('', [
        Validators.minLength(4),
        Validators.required
      ])
    });
  }

  async onLoggedin() {

    console.log('Start login... ' + this.myform.value);
    await this.httpClient.post < AuthenticationResponse > ('http://127.0.0.1:51120/login', {
        'username': this.myform.value.username,
        'password': this.myform.value.password
      })
      .toPromise().then(
        data => {
          console.log('Successfully logged in with user name: ', data.name);
          localStorage.setItem('token', data.token);
          localStorage.setItem('isLogin', 'true');
        },
        error => {
          if (!error.ok) {
            console.log('Error: ' + error.message);
          } else {
            console.log('Failed login message: ', error.error.message);
          }

          localStorage.removeItem('token');
          localStorage.removeItem('isLogin');
          this.router.navigate(['/login']);
        });

    return false;
  }
}

interface AuthenticationResponse {
  status: string;
  code: string;
  message: string;
  id: number;
  token: string;
  username: string;
  role: string;
  name: string;
  companyName: string;
}