Ошибка Angular 6 показывает, что «mat-form-field» не является известным элементом:

Привет, я использую angular 6, и мой код выглядит следующим образом:

import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';




import { AppComponent } from './app.component';
import { AppRoutingModule } from './app.routing.module';


import { MatButtonModule, MatFormFieldModule, MatInputModule, MatRippleModule } from '@angular/material';
//import { MaterialModule } from 'src/app/et-shared/material.module';


const modules = [
  MatButtonModule,
  MatFormFieldModule,
  MatInputModule,
  MatRippleModule
];

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    CommonModule,
    RouterModule,
    AppRoutingModule,
   // MaterialModule,
   ...modules

  ],
  exports:[
    ...modules
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

и html вот так

<div class="example-container">
  <mat-form-field>
    <input matInput placeholder="Input">
  </mat-form-field>

  <mat-form-field>
    <textarea matInput placeholder="Textarea"></textarea>
  </mat-form-field>

  <mat-form-field>
    <mat-select placeholder="Select">
      <mat-option value="option">Option</mat-option>
    </mat-select>
  </mat-form-field>
</div>

мой пакет, как это

"dependencies": {
    "@angular/animations": "^6.0.0",
    "@angular/cdk": "^6.0.1",
    "@angular/common": "^6.0.0",
    "@angular/compiler": "^6.0.0",
    "@angular/core": "^6.0.0",
    "@angular/forms": "^6.0.0",
    "@angular/http": "^6.0.0",
    "@angular/material": "^6.0.1",
    "@angular/platform-browser": "^6.0.0",
    "@angular/platform-browser-dynamic": "^6.0.0",
    "@angular/router": "^6.0.0",
    "core-js": "^2.5.4",
    "hammerjs": "^2.0.8",
    "rxjs": "^6.0.0",
    "zone.js": "^0.8.26"
  },

и я получаю эту ошибку

'mat-form-field' is not a known element:
1. If 'mat-form-field' is an Angular component, then verify that it is part of this module.
2. If 'mat-form-field' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("

<div class="example-container">
  [ERROR ->]<mat-form-field>
    <input matInput placeholder="Input">
  </mat-form-field>
"): ng:///AppRoutingModule/LoginComponent.html@7:2
'mat-form-field' is not a known element:
1. If 'mat-form-field' is an Angular component, then verify that it is part of this module.
2. If 'mat-form-field' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
  </mat-form-field>

  [ERROR ->]<mat-form-field>
    <textarea matInput placeholder="Textarea"></textarea>
  </mat-form-field>
"): ng:///AppRoutingModule/LoginComponent.html@11:2
'mat-option' is not a known element:
1. If 'mat-option' is an Angular component, then verify that it is part of this module.
2. If 'mat-option' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
  <mat-form-field>
    <mat-select placeholder="Select">
      [ERROR ->]<mat-option value="option">Option</mat-option>
    </mat-select>
  </mat-form-field>
"): ng:///AppRoutingModule/LoginComponent.html@17:6
'mat-select' is not a known element:
1. If 'mat-select' is an Angular component, then verify that it is part of this module.
2. If 'mat-select' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("

почему я получаю эту ошибку, мне приходится тратить слишком много времени, чтобы решить эту проблему, но я не получаю никакого решения, где я ошибаюсь. к этой ошибке

Спасибо за решение моей проблемы


person Rohit Azad Malik    schedule 14.05.2018    source источник
comment
MatFormFieldModule включен в MatInputModule, поэтому вам не нужно снова его импортировать.   -  person CornelC    schedule 14.05.2018


Ответы (8)


Глядя на вашу ошибку ng:///AppRoutingModule/LoginComponent.html@11:2

Я могу сделать вывод, что вы объявили LoginComponent в AppRoutingModule, но не импортировали туда MatFormFieldModule.

Либо переместите LoginComponent в массив declarations AppModule:

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent
  ],
  ...
})
export class AppModule { }

или импортировать MatFormFieldModule или некоторые SharedModule в AppRoutingModule:

@NgModule({
  declarations: [
    LoginComponent,
    ...
  ],
  imports: [
    MatFormFieldModule // or SharedModule that exports MatFormFieldModule
    ...
  ]
  ...
})
export class AppRoutingModule { }

Смотрите также:

person yurzui    schedule 14.05.2018
comment
да, вы правы, я пытаюсь найти это решение, чем моя проблема решена, спасибо, чувак, это просто, спаси меня +1 - person Rohit Azad Malik; 14.05.2018

Попробуйте импортировать

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

в вашем модуле, затем введите в

@NgModule({
//..your other property,
   schemas: [CUSTOM_ELEMENTS_SCHEMA]
 });
person Sanoj_V    schedule 14.05.2018
comment
Это решение помогло мне удалить ошибку. Но я не вижу кнопок на странице, только текст. - person amracel; 13.09.2018

У меня была та же проблема, исправление для меня - это MatFormFieldModule, MatInputModule, MatSelectModule, добавленные в мой модуль материалов.

import { MatFormFieldModule, MatInputModule } from '@angular/material';

@NgModule({
    imports: [
        MatFormFieldModule,
        MatInputModule
    ]
})
export class AppModule { }
person technopia3321971    schedule 02.11.2018

Вам нужно импортировать MatSelectModule:

{MatSelectModule} from '@angular/material/select';

затем добавьте его в массив импорта:

 imports: [
    BrowserModule,
    BrowserAnimationsModule,
    CommonModule,
    RouterModule,
    AppRoutingModule,
   // MaterialModule,
   ...modules,
   MatSelectModule
  ]
person Julio Rodríguez    schedule 16.09.2019

Если у вас есть 2 примера модуля приложения: app-routing.module.ts и app.module.ts импортирует CommonModule во второй (app-routing.module.ts)

person asli    schedule 10.04.2019

У меня также была эта проблема, она сводилась к неудачной установке повторной загрузки материала / установка исправила это для меня ..

добавить @angular/материал

person Jerry    schedule 02.09.2020

Если вы используете компонент material-ui, есть вкладка API, которая позволит вам узнать, какой модуль вам нужно импортировать в файл app.module.ts. https://material.angular.io/components/autocomplete/api

person geppy    schedule 08.04.2021

Я также видел это, несмотря на загрузку всех правильных модулей.

Оказывается, я забыл добавить новый компонент, обязательно добавьте его в массив declarations для модуля.

person Kildareflare    schedule 11.07.2021
comment
Рад, что ответил здесь, так как у меня снова возникла эта проблема, и я решил проблему с помощью этого ответа: 0) - person Kildareflare; 17.07.2021