typescript 特定组件中的 Angular 2 声明
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39629071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2 declarations in specific component
提问by Mix Austria
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?
上次我使用 Angular2 时,指令仍然存在,但现在 app.modules.ts 中有所谓的声明。问题是,如果我打算只在特定组件而不是主组件中使用指令,我该怎么做?
customers.component.ts
客户.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
客户.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
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.
我在想的是,当我将一个组件放在声明中时,每个组件都可以访问,而以前我只能在特定的声明中声明它。如果我在这里错了,请纠正我,并请建议在声明指令时是否有更好的选择。
回答by tibbus
You can put the component declaration into a Feature Module.
The Feature Moduleshould be imported into the App Module.
您可以将组件声明放入Feature Module。
所述特征模块应该被导入到APP模块。
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.
现在这取决于您是否认为您的组件是一个功能并且是否值得一个单独的模块。
我知道模块的所有这些事情并不像指令那样简单和清晰,但是 Angular2 中的一些设计问题无法通过其他方式解决。
Documentation : https://angular.io/guide/feature-modules