< EM> декламация
Я предвосхищу это, сказав, что мой первый пост был грубо закрыт кем-то, занимавшимся кармическим земледелием, пометив мой пост как закрытый, когда предоставленное решение не работает И связанная «дублирующая» публикация показала то же решение, которое я продемонстрировал и попробовал в своем оригинальном посте, поэтому я был бы признателен коллегам-SO из браузеров, чтобы не быть таким пренебрежительным, и полностью прочитать мой пост, прежде чем слепо принять решение закрыть его после демонстрация решения, которое не решило мой начальный вопрос.
конец разговора
Я пытаюсь создать форму входа в Angular 9. Я понимаю распространенную проблему в Angular с формами из-за того, что не импортировал FormsModule в @NgModule
Однако я импортировал FormsModule и ReactiveFormsModule, и это не решило мою проблему
//from app.module.ts
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
ForumComponent,
PostComponent,
UserComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MaterialModule,
FormsModule,
FormBuilder,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent],
})
Ниже приведен HTML-код для моей формы в файле login.component.html, который, как я покажу, позже я немного реорганизовал.
<form class="box" action="" #loginForm="ngForm" (ngSubmit)="login()">
<div class="field">
<label for="" class="label">Email</label>
<div class="control has-icons-left">
<input type="email"
placeholder="e.g. bobsmith@rpi.edu"
class="input"
[(ngModel)] = "model.email"
required />
<span class="icon is-small is-left">
<i class="fa fa-envelope"></i>
</span>
</div>
</div>
<div class="field">
<label for="" class="label">Password</label>
<div class="control has-icons-left">
<input type="password"
placeholder="*******"
class="input"
[(ngModel)] = "model.password"
required />
<span class="icon is-small is-left">
<i class="fa fa-lock"></i>
</span>
</div>
</div>
<div class="field">
<label for="" class="checkbox">
<input type="checkbox" />
Remember me
</label>
</div>
<div class="field">
<button class="button is-success" [disabled]="!loginForm.valid">
Login
</button>
</div>
</form>
В первоначальном ответе / ответе на мое первое сообщение предлагалось добавить formControlName к тегам <input>
, но затем его поспешно отредактировали, чтобы сказать, что [(ngModel)]
устарела. Прежде чем я смог вставить и продемонстрировать, что это все еще не работает, мой пост был закрыт.
Так как anon считает, что знает, что его решение работает, позвольте мне поделиться с вами моей текущей настройкой формы HTML. Я следовал за документами для FormBuilder, и это то, к чему это привело.
<!-- LATEST HTML -->
<form class="box" action="" [formGroup]="loginForm" (ngSubmit)="login()">
<div class="field">
<label for="" class="label">Email</label>
<div class="control has-icons-left">
<input type="email"
placeholder="e.g. bobsmith@rpi.edu"
class="input"
formControlName = "email"
required />
<span class="icon is-small is-left">
<i class="fa fa-envelope"></i>
</span>
</div>
</div>
<div class="field">
<label for="" class="label">Password</label>
<div class="control has-icons-left">
<input type="password"
placeholder="*******"
class="input"
formControlName = "password"
required />
<span class="icon is-small is-left">
<i class="fa fa-lock"></i>
</span>
</div>
</div>
<div class="field">
<label for="" class="checkbox">
<input type="checkbox" />
Remember me
</label>
</div>
<div class="field">
<button class="button is-success" [disabled]="!loginForm.valid">
Login
</button>
</div>
</form>
И в моем файле login.component.ts, это то, что у меня есть
import { Component, OnInit } from "@angular/core";
import { Router } from "@angular/router";
import { AuthService } from 'src/app/auth.service';
import { FormBuilder } from '@angular/forms';
@Component({
selector: "app-login",
templateUrl: "./login.component.html",
styleUrls: ["./login.component.css"],
})
export class LoginComponent implements OnInit {
model: any = {};
loginForm;
constructor(
private authService: AuthService,
private router: Router,
private formBuilder: FormBuilder
) {
this.loginForm = this.formBuilder.group({
email: '',
password: ''
});
}
ngOnInit(): void { }
login() {
this.authService.login(this.model).subscribe(
next => {
this.router.navigate(['/home']);
},
error => {
throw new Error("ERROR: Login failed");
}
);
}
}
Хорошо, круто, рефакторинг точно в соответствии со спецификациями в соответствии с официальными Angular Docs на FormBuilder. Ну, это ошибка, которая сбрасывается в мою консоль, когда я пытаюсь обслуживать приложение Angular.
ERROR in src/app/components/login/login.component.html:6:34 - error NG8002: Can't bind to 'formGroup' since it isn't a known property of 'form'.
line 6 <form class="box" action="" [formGroup]="loginForm" (ngSubmit)="login()">
~~~~~~~~~~~~~~~~~~~~~~~
src/app/components/login/login.component.ts:8:15
line 8 templateUrl: "./login.component.html",
~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component LoginComponent.
Как уже было показано, дважды теперь форма не компилируется — даже если точно следовать документам. Я был бы признателен за любую помощь, которую я могу получить, так как эта проблема вела меня на несколько часов вверх по стене. Спасибо
The issue is caused by package @angular/….
"@angular/animations": "~10.1.4",
"@angular/common": "~10.1.4",
"@angular/compiler": "~10.1.4",
"@angular/core": "~10.1.4",
"@angular/forms": "~10.1.4",
"@angular/platform-browser": "~10.1.4",
"@angular/platform-browser-dynamic": "~10.1.4",
"@angular/router": "~10.1.4",
"rxjs": "~6.6.0",
"tslib": "^2.0.0",
"zone.js": "~0.10.2"
Description
Dev server error is present when template error is fixed
🔬 Minimal Reproduction
install the latest version of @angular/cli
I am using
"@angular/cli": "~10.1.4",
create a brand new app like
In app.component.html, copy and paste the following line inside of the main content div:
<h1 [style.color]="'red'">Hello World!</h1>
Change the first double quote to single quote to cause the template error. Then change it back to double quote to fix it.
In the terminal, these errors are shown:
ERROR in src/app/app.module.ts:9:5 - error NG6001: The class 'AppComponent' is listed in the declarations of the NgModule 'AppModule', but is not a directive, a component, or a pipe. Either remove it from the NgModule's declarations, or add an appropriate Angular decorator.
9 AppComponent
~~~~~~~~~~~~
src/app/app.component.ts:8:14
8 export class AppComponent {
~~~~~~~~~~~~
'AppComponent' is declared here.
src/app/app.component.html:417:25 - error NG8002: Can't bind to 'ngSwitch' since it isn't a known property of 'div'.
417 <div class="terminal" [ngSwitch]="selection.value">
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/app/app.component.ts:5:16
5 templateUrl: './app.component.html',
~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component AppComponent.
src/app/app.component.html:535:1 - error NG8001: 'router-outlet' is not a known element:
1. If 'router-outlet' is an Angular component, then verify that it is part of this module.
2. If 'router-outlet' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
535 <router-outlet></router-outlet>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/app/app.component.ts:5:16
5 templateUrl: './app.component.html',
~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component AppComponent.
You can read more about issue submission guidelines here:
🌍 Your Environment
It’s a brand new angular app as of 10/6/2020:
«dependencies»: {
«@angular/animations»: «~10.1.4»,
«@angular/common»: «~10.1.4»,
«@angular/compiler»: «~10.1.4»,
«@angular/core»: «~10.1.4»,
«@angular/forms»: «~10.1.4»,
«@angular/platform-browser»: «~10.1.4»,
«@angular/platform-browser-dynamic»: «~10.1.4»,
«@angular/router»: «~10.1.4»,
«rxjs»: «~6.6.0»,
«tslib»: «^2.0.0»,
«zone.js»: «~0.10.2»
},
«devDependencies»: {
«@angular-devkit/build-angular»: «~0.1001.4»,
«@angular/cli»: «~10.1.4»,
«@angular/compiler-cli»: «~10.1.4»,
«@types/node»: «^12.11.1»,
«@types/jasmine»: «~3.5.0»,
«@types/jasminewd2»: «~2.0.3»,
«codelyzer»: «^6.0.0»,
«jasmine-core»: «~3.6.0»,
«jasmine-spec-reporter»: «~5.0.0»,
«karma»: «~5.0.0»,
«karma-chrome-launcher»: «~3.1.0»,
«karma-coverage-istanbul-reporter»: «~3.0.2»,
«karma-jasmine»: «~4.0.0»,
«karma-jasmine-html-reporter»: «^1.5.0»,
«protractor»: «~7.0.0»,
«ts-node»: «~8.3.0»,
«tslint»: «~6.1.0»,
«typescript»: «~4.0.2»
}
|
# |
|
Date 07.04.2021 |
Views 46.568 |
Error Message in
VSCode Terminal:
Error: src/app/xxx.component.html:24:5
— error NG8001: ‘mat-icon’ is not a known element:
1. If ‘mat-icon’ is an Angular component,
then verify that it is part of this module.
2. If ‘mat-icon’ is a Web Component then
add ‘CUSTOM_ELEMENTS_SCHEMA’ to the ‘@NgModule.schemas’ of this component to
suppress this message.
24
<mat-icon>home</mat-icon>
~~~~~~~~~~
src/app/articles/read-article/read-article.component.ts:13:16
13 templateUrl:
‘./read-article.component.html’,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component
ReadArticleComponent.
solution:
You have to
insert the missing module in app.modules.ts
In this case, it
is the mat-icon -> MatIconmodule
from @angular/material/icon
ClientApp/src/app/
<div >
<button mat-fab color=»warn» aria-label=»Example icon button with a home
icon»>
<mat-icon>home</mat-icon>
</button>
</div>
app.module.ts
import { BrowserModule } from ‘@angular/platform-browser’;
import { NgModule } from ‘@angular/core’;
import { FormsModule } from ‘@angular/forms’;
import { HttpClientModule, HTTP_INTERCEPTORS }
from ‘@angular/common/http’;
//*Material-UI
//*@Angular-Material
import { MatIconModule } from ‘@angular/material/icon’;
import { MatButtonModule } from ‘@angular/material/button’;
//*routing replaces import {
RouterModule } from ‘@angular/router’;
import { AppRoutingModule } from ‘./app-routing.module’; //*Routing in app-routing.module.ts
//Asp Auth Identiy
import { ApiAuthorizationModule } from ‘src/api-authorization/api-authorization.module’;
import { AuthorizeGuard } from ‘src/api-authorization/authorize.guard’;
import { AuthorizeInterceptor } from ‘src/api-authorization/authorize.interceptor’;
//App Components
import { AppComponent } from ‘./app.component’;
import { NavMenuComponent } from ‘./nav-menu/nav-menu.component’;
import { HomeComponent } from ‘./home/home.component’;
import { ListArticlesComponent } from ‘./articles/list-articles/list-articles.component’;
import { EditArticleComponent } from ‘./articles/edit-article/edit-article.component’;
import { ReadArticleComponent } from ‘./articles/read-article/read-article.component’;
@NgModule({
declarations: [
AppComponent,
NavMenuComponent,
HomeComponent,
ListArticlesComponent,
EditArticleComponent,
ReadArticleComponent,
],
imports: [
BrowserModule.withServerTransition({ appId: ‘ng-cli-universal’ }),
HttpClientModule,
FormsModule,
MatIconModule, //*FAB
Button
MatButtonModule, //*FAB Button
ApiAuthorizationModule,
AppRoutingModule
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthorizeInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }
#angular
#angular
Вопрос:
Я знаю, что этот вопрос задавался много раз, но все решения, которые я нашел, не решили мою проблему. Это моя форма в HTML-файле компонента входа:
<form #loginForm="ngForm" (ngSubmit)="login()">
<p *ngIf="errorMessage" class="error">{{ errorMessage }}</p>
<p class="username">User Name</p>
<input type="text" placeholder="Enter user name" name="username" [(ngModel)]="model.username">
<p class="password">Password</p>
<input type="password" class="centered-items" placeholder="Enter password" name="password" [(ngModel)]="model.password">
<hr>
<button class="login-btn" type="submit">Login</button>
<button [routerLink]="['../']">Cancel</button>
<p>Not registered? <a [routerLink]="['../register']">Register now</a></p>
</form>
Это мой метод входа в систему в файле login component .ts:
login() {
this.databaseService.login(this.model).subscribe(() => {
}, error => {
this.errorMessage = error.error;
}, () => {
this.route.navigate(['../']);
});
}
Это ошибка, получаемая в консоли:
src/app/login/login.component.ts:8:16
8 templateUrl: './login.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component LoginComponent.
src/app/register/register.component.html:6:27 - error NG8003: No directive found with exportAs 'ngForm'.
Я добавил FormsModule и ReactiveFormsModule как в файлы app.module, так и в login.module. Я перезапустил VS code и попытался запустить обновление npm. Я также попытался удалить # из #LoginForm, как было предложено в одном сообщении.
Комментарии:
1. Вы импортировали FormsModule?
2. Какова ваша версия Angular?
3. Я думаю
#loginForm="ngForm"
, что должно быть(formGroup)="ngForm"
4. похоже, что версия, которую я использую, 9.1.7. Я импортировал FormsModule. Использование (FormGroup)=»ngForm» выдает ошибку: «Идентификатор ‘ngForm’ не определен. Объявление компонента, объявления переменных шаблона и ссылки на элементы не содержат такого элемента »
5. Я обновил Angular до версии 10, но у меня все та же проблема
Ответ №1:
Добавление LoginComponent в объявления файла app.module решило эту проблему для меня