fugigoose fugigoose - 4 months ago 8
AngularJS Question

Understanding Order of Definitions in TypeScript/Angular JS

So maybe this is a total noob question, but I am a total noob at Angular JS and TypeScript. I'm going through Angular's hero tutorial (There's a Plunker for it here: https://angular.io/resources/live-examples/toh-1/ts/plnkr.html). If the Hero class is defined at the beginning (after the import line) or end of the file, it runs fine; however, if it's defined in between @Component and AppComponent, the JS throws the following exception at runtime: "No Directive annotation found on AppComponent". I don't understand enough about TypeScript and/or Angular JS to satisfactorily understand why this is. Why is the order so important? Do I need to add some special syntax when the Hero definition is in the middle? Thanks!

Answer

@Component, or any similar thing that starts with an @ symbol, is a special language element called an annotation. It is associated with the code element (class, variable, etc.) that immediately follows it, and specifies metadata of some kind about that code element. In this case, @Component specifies that the class it is attached to is an Angular component.

When you have the Hero class between @Component and AppComponent, you are declaring that Hero, not AppComponent, is an Angular component because Hero is the code element immediately following @Component.