Angular 2 declarations in specific component

╄→гoц情女王★ 提交于 2019-12-07 10:24:48

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/39629071/angular-2-declarations-in-specific-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!