Mix Austria
Mix Austria

Reputation: 935

Angular 2 declarations in specific component

Last time I use Angular2 the directives are still present but now there is so called declarations in app.modules.ts. Question is, if I am going to use a directive only in specific component and not on the main, how can I do that?

customers.component.ts

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

@Component({
    selector: 'app-customers',
    templateUrl: 'app/customer/customers.component.html'
})

export class CustomersComponent {
    customers = [
    { id: 1, name: 'Mix'},
    { id: 2, name: 'Ian'},
    { id: 3, name: 'Aniel'},
    { id: 4, name: 'Jess'},
    { id: 5, name: 'Jusi'},
    ];
}

customer.component.ts

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

@Component({
    selector: 'app-customer',
    templateUrl: 'app/customer/customer.component.html'
})

export class CustomerComponent {
    @Input() customer: {id: number, name: string};

    myColor = 'gray';
}

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent }  from './app.component';
import { CustomerComponent } from './customer/customer.component';
import { CustomersComponent } from './customer/customers.component';

@NgModule({
  imports: [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, CustomerComponent, CustomersComponent ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

What am I thinking is when I put a component in a declaration, every component can access that unlike before that I can only declare it in a specific. Please correct me if I'm wrong here and please suggest if there is a better alternative in declaring directives.

Upvotes: 4

Views: 15282

Answers (1)

Tiberiu Popescu
Tiberiu Popescu

Reputation: 4524

You can put the component declaration into a Feature Module.
The Feature Module should be imported into the App Module.

Now it's up to you if you consider that your component it's a feature and deserve a separate Module or not.
I'm aware that all this thing with the modules is not so simple and clear as it was with the directives, but there were some design things in Angular2 that couldn't be resolved in other way.

Documentation : https://angular.io/guide/feature-modules

Upvotes: 6

Related Questions