简体   繁体   English

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

[英]Angular 6 form template error: 'There is no directive with “exportAs” set to “ngForm”'

I have downloaded Angular 6 + bootstrap 4 free skin - https://startangular.com/product/sb-admin-bootstrap-4-angular-6/ When trying to use I continuously getting error: There is no directive with "exportAs" set to "ngForm". 我已经下载角6 + 4引导游离皮- https://startangular.com/product/sb-admin-bootstrap-4-angular-6/当尝试使用我不断收到错误:没有与“EXPORTAS”没有指令设置为“ ngForm”。

My app.module.ts: 我的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);

My login.component.ts: 我的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;
    }

My login.component.html: 我的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>

All over got replies asking to add to @NgModule({ imports: [ FormsModule, ReactiveFormsModule, 到处都有答复要求添加到@NgModule({导入:[FormsModule,ReactiveFormsModule,

But it does not work for me at all. 但这对我根本不起作用。 Please advise 请指教

There's an issue with your Template: 您的模板存在问题:

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

Here you're using #f="ngForm" which is generally used for Template Driven Forms and you're creating a Reactive Form in your TypeScript class. 在这里,您使用的是#f="ngForm" ,通常用于“模板驱动表单”,并在TypeScript类中创建“反应性表单”。

You should be using either one of them but not both at the same time in the same Component. 您应该在同一组件中同时使用其中之一,但不能同时使用。

You'll anyway have access to the form in your Component Class. 无论如何,您都可以访问组件类中的表单。

onLoggedin can directly access the form using this.myform onLoggedin可以使用this.myform直接访问表单

To fix the issue, get rid of #f="ngForm" from your template: 要解决此问题,请从模板中#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>

And in your Component Class: 在您的组件类中:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular:“exportAs”设置为“ngForm”的错误无指令 - Angular: Error no directive with "exportAs" set to "ngForm" Angular2 错误:没有将“exportAs”设置为“ngForm”的指令 - Angular2 Error: There is no directive with "exportAs" set to "ngForm" Angular / NgForm / NgModel指令错误:没有将“ exportAs”设置为“ ngForm”的指令 - Angular/ NgForm/NgModel directives error : There is no directive with “exportAs” set to “ngForm” Angular 4-没有将“ exportAs”设置为“ ngForm”的指令 - Angular 4 - There is no directive with “exportAs” set to “ngForm” angular 中没有将“exportAs”设置为“ngForm”的指令 - There is no directive with "exportAs" set to "ngForm" in angular TypeScript- 的 Angular 框架错误 - “没有将 exportAs 设置为 ngForm 的指令” - TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm" Angular2问题:“exportAs”设置为“ngForm”没有指令 - Angular2 issue: There is no directive with “exportAs” set to “ngForm” 没有将“exportAs”设置为“ngForm”的指令 - There is no directive with “exportAs” set to “ngForm” 这里没有将“exportAs”设置为“ngForm”的指令 - here is no directive with “exportAs” set to “ngForm” Angular `12.1.2 错误 NG8003:未找到带有 exportAs &#39;ngForm&#39; 的指令 - Angular `12.1.2 error NG8003: No directive found with exportAs 'ngForm'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM