我对angular完全陌生,我正在练习使用材质并添加表单字段。我遵循了所有指南,下载了所有软件包,我的代码只是从指南中复制粘贴而来,但仍未显示在我的浏览器中。
我的控制台初始显示
“模块'AppModule'导入了意外指令'MatFormField'。请添加@NgModule批注。”
在谷歌搜索之后,我被告知要用“ MatFormFieldModule”替换它,但是在我这样做之后,我得到了这个错误
“ NullInjectorError:StaticInjectorError(AppModule)[CdkObserveContent-> ElementRef]: StaticInjectorError(平台:核心)[CdkObserveContent-> ElementRef]: NullInjectorError:没有ElementRef的提供者!”
我的代码:
app.component.html
<p>works</p>
<form class = "tp-form">
<mat-form-field class = "tp-full-width">
<input matInput placeholder = "Favorite Food" value = "Pasta">
</mat-form-field>
<mat-form-field class = "tp-full-width">
<textarea matInput placeholder = "Enter your comment"></textarea>
</mat-form-field>
<mat-form-field class = "tp-full-width">
<input matInput placeholder = "Email" [formControl] =
"emailFormControl">
<mat-error *ngIf = "emailFormControl.hasError('email')
&& !emailFormControl.hasError('required')">
Please enter a valid email address
</mat-error>
<mat-error *ngIf = "emailFormControl.hasError('required')">
Email is <strong>required</strong>
</mat-error>
</mat-form-field>
</form>
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CourseComponent } from './course/course.component';
import {BrowserAnimationsModule} from '@angular/platform-
browser/animations';
import {MatInputModule, MatFormField, MatFormFieldModule} from
'@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
const modules = [
BrowserAnimationsModule,
MatInputModule,
FormsModule,
ReactiveFormsModule,
MatFormFieldModule
]
@NgModule({
declarations: [
AppComponent,
CourseComponent
],
imports: [
BrowserModule,
AppRoutingModule,
...modules
],
exports:[
...modules
],
providers: [],
bootstrap: [AppComponent]
,
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
import { FormControl } from "@angular/forms";
import { Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'materialApp';
emailFormControl = new FormControl('', [
Validators.required,
Validators.email,
]);
}
当前我的浏览器仅显示“作品”。
答案 0 :(得分:0)
emailFormControl
应该使用ViewChild
注释定义,如下所示:
import { Component, ElementRef, ViewChild } from '@angular/core'
...
@ViewChild('emailFormControl') emailFormControl: ElementRef
简而言之,ViewChild
允许我们查询元素(来自文档:https://angular.io/api/core/ViewChild)
在此示例中,我们使用emailFormControl
的查询目标获取有效的引用