Проблемы с привязкой ngModel и импортом ngForm, хотя весь код выглядит хорошо. Столкнувшись со многими более странными проблемами, есть проблемы с версией Angular? - PullRequest
2 голосов
/ 06 апреля 2020
ERROR in src/app/Register/register.component.html:12:9 - error NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'.

12         [(ngModel)]="model.UserName"
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  src/app/Register/register.component.ts:6:16
    6   templateUrl: "./register.component.html",
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component RegisterComponent.
src/app/Register/register.component.html:3:24 - error NG8003: No directive found with exportAs 'ngForm'.

3   <form #registerForm="ngForm">
                         ~~~~~~

  src/app/Register/register.component.ts:6:16
    6   templateUrl: "./register.component.html",
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component RegisterComponent.

Эта ошибка продолжает появляться - я все проверил, все выглядит хорошо. Пробовал много раз. Я подозреваю Angular версию или проблемы с зависимостями, поскольку я получаю странные проблемы. Я проверил много онлайн примеров, не вижу ничего плохого в моем коде.

Вот мой app.module.ts

import { BrowserModule } from "@angular/platform-browser";
import { AppRoutingModule } from "./app-routing.module";
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
import { AppComponent } from "./app.component";
import { LoginComponent } from "./login/login.component";
import { RegisterComponent } from "./register/register.component";
import { TasksComponent } from "./tasks/tasks.component";
import { TemplatesComponent } from "./templates/templates.component";
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
import { MatTabsModule } from "@angular/material/tabs";
import { MatButtonModule } from "@angular/material/button";
import { MatButtonToggleModule } from "@angular/material/button-toggle";

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    RegisterComponent,
    TasksComponent,
    TemplatesComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatTabsModule,
    MatButtonModule,
    MatButtonToggleModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

Вот мой регистрационный модуль ШАБЛОН:

<div class="container">
  <h1>Registration Form</h1>
  <form #registerForm="ngForm">
    <div class="form-group">
      <label for="name">Name</label>
      <input
        type="text"
        class="form-control"
        id="name"
        required
        [(ngModel)]="model.UserName"
      />
    </div>

    <div class="form-group">
      <label for="alterEgo">Alter Ego</label>
      <input type="text" class="form-control" id="alterEgo" />
    </div>

    <button type="submit" class="btn btn-success">Submit</button>
  </form>
</div>

Регистрационный файл TS:

import { RegistrationModel } from "./../model/RegistrationModel";
import { Component, OnInit } from "@angular/core";

@Component({
  selector: "app-register",
  templateUrl: "./register.component.html",
  styleUrls: ["./register.component.css"]
})
export class RegisterComponent implements OnInit {
  constructor() {}
  model = new RegistrationModel();
  ngOnInit(): void {}
}

Модуль маршрутизатора TS

import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import { LoginComponent } from "./Login/login.component";
import { RegisterComponent } from "./Register/register.component";
import { TasksComponent } from "./tasks/tasks.component";
import { TemplatesComponent } from "./templates/templates.component";

const routes: Routes = [
  { path: "", redirectTo: "login", pathMatch: "full" },
  { path: "login", component: LoginComponent },
  { path: "register", component: RegisterComponent },
  { path: "tasks", component: TasksComponent },
  { path: "templates", component: TemplatesComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

Файл RegistrationModel.ts:

import { Time } from "@angular/common";

export class RegistrationModel {
  private userId: number;
  private userName: string;
  private active: boolean;
  private createTimeStamp: Time;
  private dayPhoneNumber: string;
  private eveningPhoneNumber: string;
  private cellPhoneNumber: string;
  private addressStreet: string;
  private city: string;
  private state: string;
  private country: string;
  private password: string;
  private emailAddress: string;

  get UserId() {
    return this.userId;
  }

  set UserId(value) {
    this.userId = value;
  }

  get UserName() {
    return this.userName;
  }

  set UserName(value) {
    this.userName = value;
  }

  get Active() {
    return this.active;
  }

  set Active(value) {
    this.active = value;
  }

  get CreateTimeStamp() {
    return this.createTimeStamp;
  }

  set CreateTimeStamp(value) {
    this.createTimeStamp = value;
  }

  get DayPhoneNumber() {
    return this.dayPhoneNumber;
  }

  set DayPhoneNumber(value) {
    this.dayPhoneNumber = value;
  }

  get CellPhoneNumber() {
    return this.cellPhoneNumber;
  }

  set CellPhoneNumber(value) {
    this.cellPhoneNumber = value;
  }

  get EveningPhoneNumber() {
    return this.eveningPhoneNumber;
  }

  set EveningPhoneNumber(value) {
    this.eveningPhoneNumber = value;
  }

  get AddressStreet() {
    return this.addressStreet;
  }

  set AddressStreet(value) {
    this.addressStreet = value;
  }

  get City() {
    return this.city;
  }

  set City(value) {
    this.city = value;
  }

  get State() {
    return this.state;
  }

  set State(value) {
    this.state = value;
  }

  get Country() {
    return this.country;
  }

  set Country(value) {
    this.country = value;
  }

  get EmailAddress() {
    return this.emailAddress;
  }

  set EmailAddress(value) {
    this.emailAddress = value;
  }

  get Password() {
    return this.password;
  }

  set Password(value) {
    this.password = value;
  }

  constructor() {}
}

Пакет. json файл

{
  "name": "gui7",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.0.5",
    "@angular/cdk": "^9.1.3",
    "@angular/common": "~9.0.5",
    "@angular/compiler": "~9.0.5",
    "@angular/core": "~9.0.5",
    "@angular/forms": "~9.0.5",
    "@angular/material": "^9.1.3",
    "@angular/platform-browser": "~9.0.5",
    "@angular/platform-browser-dynamic": "~9.0.5",
    "@angular/router": "~9.0.5",
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.5",
    "@angular/cli": "~9.0.5",
    "@angular/compiler-cli": "~9.0.5",
    "@angular/language-service": "~9.0.5",
    "@types/node": "^12.11.1",
    "@types/jasmine": "~3.5.0",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~2.1.0",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "~5.4.3",
    "ts-node": "~8.3.0",
    "tslint": "~5.18.0",
    "typescript": "~3.7.5"
  }
}

1 Ответ

0 голосов
/ 06 апреля 2020

Я могу посоветовать вам добавить директиву "ngForm" к вашему тегу "form".

<form ngForm #registerForm="ngForm"></form

Несомненно, есть еще одна ошибка, которая придет сразу за вами. Чтобы настроить его, вам, вероятно, придется добавить атрибут «name» к вашему входу.

<input
    type="text"
    class="form-control"
    id="name"
    required
    [(ngModel)]="model.UserName"
  />

К

<input
    type="text"
    class="form-control"
    id="name"
    name="azerty"
    required
    [(ngModel)]="model.UserName"
  />
...