Angular2 - getting error as : `EXCEPTION: No Direc

2020-04-05 19:30发布

问题:

when i trying to import a directive from other file, i am getting the error as EXCEPTION: No Directive annotation found on MyComponent - how to solve this?

here is my code:

app.component.ts:

import {Component} from 'angular2/core';
import {MyComponent} from "./app.my-component"

@Component({
    selector: 'app',
    template: `
        <h1>Hellow World</h1>
        <span>Here is your component:</span>
        <my-component></my-component>
    `,
    directives: [MyComponent]
})

export class AppComponent { }

app.mycomponent.ts:

import {Component} from 'angular2/core';

@Component({

    selector : 'my-component',

    template : `<h2>This is from My component</h2>`

});

export class MyComponent { };

But i am getting error as : No Directive annotation found on MyComponent how to solve this?

回答1:

You should remove ; after component closing Component directive parenthesis.

import {Component} from 'angular2/core';

@Component({

selector : 'my-component',

template : `<h2>This is from My component</h2>`

})
export class MyComponent { };


回答2:

Maybe you have to make a relative path instead. It depends of where the component you want to import is located relative to the script you are importing the component in. Something like

import {MyComponent} from "../app.my-component"

or

import {MyComponent} from "./app.my-component".

It would help if you posted your folder structure as well.



回答3:

oke, i am also still 'learning' on this, but i got the same message as you did. i think i solved it...

found my answer here: https://angular.io/docs/ts/latest/guide/attribute-directives.html

add this to your app.mycomponent.ts:

import {Directive} from 'angular2/core';

and add the directive:

@Directive({
    selector: '[MyComponent]'
})

hope this helps you a bit.

Again, NOT sure if this is the right way...



回答4:

In my case, there was a problem with the export of a particular class, and the importing of that class in other components.

But this error was not shown explicitly, instead it manifested as the exception in EXCEPTION: No Directive annotation... in the console.

In order to get this error explicitly:

  1. Stop the local server
  2. Re-run npm start (assuming the Angular quickstart setup)

Any current errors that were previously hidden will show up immediately.



标签: angular