如何在angular2中使用指令

时间:2016-10-20 06:45:23

标签: angular typescript

我想在我的app.component.html中为我使用的指令加载我的navbar.html,然后按照以下方法,

我的navbar 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>

这是我的情况,我不确定如何解决,任何人都可以建议我帮忙。谢谢。

2 个答案:

答案 0 :(得分:3)

您的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: [],
})

答案 1 :(得分:3)

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

现在他们应该在

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

另见