网站搜索

angular - 如何在 angular2 中使用指令


我想在我的 app.component.html 中加载我的 navbar.html,为此我使用了指令并遵循了以下方法,

我的导航栏 HTML,

<p>Hi i am a pen</p>

我的 navbar.ts,

 import {Component,Directive, OnInit} from '@angular/core';
    @Component({
    selector: 'header-Navbar',
    templateUrl: './app/navbar/navbar.html',
     })
    export class Navbar  {}

我的 app.component.html,

    <header-Navbar></header-Navbar>

我的 app.component.ts,

import {Component,Directive, OnInit} from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
import { Http, Headers } from '@angular/http';
import { Navbar }  from '../navbar/navbar';
import {PathLocationStrategy, LocationStrategy, Location} from '@angular/common';
import { Config } from '../headers';
@Component({
    selector: 'my-app',
    directives : [Navbar],---->Saying type error
    templateUrl: './app/components/app.component.html',
    providers: [Config]
})

我的错误

   'header-Navbar' is not a known element:
1. If 'header-Navbar' is an Angular component, then verify that it is part of this module.
2. If 'header-Navbar' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("
        [ERROR ->]<header-Navbar></header-Navbar>

这是我的情况,我不确定该如何解决,有人能给我一些建议吗?谢谢。

答案#1

@Component() 中的 directives 已经消失有一段时间了。

现在它们应该在里面

@NgModule({
  declarations: [NavBar]
  ...
}
export class AppModule {} 
// or 
export class MyOtherModule {}

另请参阅

  • https://angular.io/docs/ts/latest/guide/ngmodule.html
  • https://angular.io/docs/ts/latest/cookbook/ngmodule-faq.html

答案#2

你的 app.component

@Component({ // <--- removed directives
    selector: 'my-app',
    templateUrl: './app/components/app.component.html',
    providers: [Config]
})

你的 app.module

import { Navbar }  from '../navbar/navbar';
@NgModule({
    imports: [],
    exports: [],
    declarations: [Navbar], // <-- imported here
    providers: [],
})