可重用组件/指令 ng2

Reuseable Components / Directives ng2

我有一个这样的导航组件:

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

const template = require('./navigation.jade');
const styles = require('./navigation.sass');

@Component({
    selector: 'navigation',
    templateUrl: template,
    styleUrls: [styles]
})

export class NavComponent {

 }

与其手动将其添加到每一页的页眉,不如将其包含在我的 app.component.ts 文件中。

目前我的实现如下:

import {Component, ViewEncapsulation} from '@angular/core';
import {ROUTER_DIRECTIVES} from '@angular/router';

import {NavComponent} from './components/navigation/navigation.component';

const styles = require('./base-styles.sass');

@Component({
    selector: 'app',
    directives: [ROUTER_DIRECTIVES, NavComponent],
    encapsulation: ViewEncapsulation.None,
    styles: [styles],
    template: `
    <navigation></navigation>
    <div class="container">
<router-outlet></router-outlet>
    </div>`
})
export class AppComponent {
}

但是导入 Component 然后将其包含为 Directive 选择器感觉不对,我确定这是不正确的,我怎样才能最好地做到这一点?

如果我尝试将其转换为指令,我无法在模板文件中要求并将我的导航栏导入 DOM。

我是 ng 的新手,热衷于只学习最佳实践,这可能有效,但感觉有点 'hacky...'

您可以全局提供指令

provide({provide: PLATFORM_DIRECTIVES, useValue: [NavComponent], multi: true})

但总的来说,您的操作方式是首选方式。

像往常一样,Gunter 的评论是正确的 :) 作为指令导入和使用是正确的方法(如果您希望 nav 成为它自己的组件)。此外,如果您对所有 angular 最佳实践感兴趣,那么 angular.io 就是您要去的地方。