gustavo galindo
gustavo galindo

Reputation: 3

How can I use Angular/Materials without using NgModule and only Using 'Component' from /core?

I have a functional application built with the Angular CLI v-13.2.6 and I just want to add the great features of angular material forms and icons. I am already using the Component decorator in my class therefore I get an error when trying to use NgModule.

My question is, Is there any way to implement Angular/Material with that Component decorator on my class/without NgModule? Or, is there any way to get float-forms without using Angular Material?

I followed all instructions here: https://material.angular.io/guide/getting-started.

install materials -> ng add @angular/material

import component to .ts ->

import { Component, NgModule, OnInit } from '@angular/core';
import { MatFormFieldModule } from '@angular/material/form-field';

@NgModule({
  imports: [
    MatFormFieldModule,
  ]
})

However when run the app I get the following angular error:

N1006 two incompatible decorators on class.

From what I have read I understand that I cannot have 2 decorators on the same class.

This is what is in the existing code and I am not allowed to change it:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-pagexx',
  templateUrl: './pagexx.html',
  styleUrls: ['./pagexx.scss']
})

Upvotes: 0

Views: 1098

Answers (1)

D M
D M

Reputation: 7189

You should have a bootstrapped module in your application (it's called AppModule by default and can be found at src/app/app.module.ts). You import the feature modules from Material by adding them to the imports array for your default module:

import { FooComponent } from './foo/foo.component';
import { MatFormFieldModule } from '@angular/material/form-field';

@NgModule({
  declarations: [
    FooComponent          /* <-- Your components/pages */
  ],
  imports: [
    MatFormFieldModule    /* <-- Any Material imports */
  ]
})
export class AppModule { }

Then you can use the imported feature in your components. You don't have to add anything to your @Component decorator:

@Component({
  selector: 'app-foo',
  template: './foo.component.html',
  styles: []
})
export class FooComponent { }
<p>This is the template for FooComponent.</p>
<mat-form-field>
  <input placeholder="Start typing...">
</mat-form-field>

Upvotes: 2

Related Questions