In the first post of this series, I’ve given an introduction to angular 2. We are now ready to delve into its particulars.
An Angular 2 app has four key players.
Let’s discuss each of them in more details…
- It is a basic building block of Angular application that controls the screen view through its associated template.
- It encapsulates the template, data and the behavior of a view, more accurately called a view component.
- Every Angular app will have at least one component. However, real world applications consist of multiple components. Each component will have html template for the view as well as data and logic behind that view.
- Component is decorated with a decorator. The decorator or (annotation as said in Java) adds metadata about this class.
- This architecture allows breaking a large application with complex views to multiple components making it more manageable.
- How do components look in code? They are plain typescript class with properties and methods. Properties hold data for view and methods implement behavior of view (like what should happen when a button is clicked).
- How does angular know that this file is going to be a component since all are typescript files? Angular looks for specific attributes or metadata in a class (specifically selector and template). Also, it requires that the “Component” decorator is imported from Angular module and it has to be applied to the class. (A decorator is a function that needs to be called; it is like an attribute in C# or an annotation in Java).
- A service is a plain typescript file that encapsulates any non-UI logic like making http calls, logging, business rules, etc.
- Sometimes components need to talk to back-end APIs to get or save data.
- Any logic that is not related to a view is delegated to a service to have good separation of concerns in the laptop.
- This is another key player that is purely responsible for navigation.
- As the user navigates from one page to another, it will figure out based on changes in URL and optional parameters what component to present to the user.
- Directives are similar to components, often used to add behavior to existing elements.
- But, unlike a component, a directive doesn’t have a template or html markup for view.
- Ex – We can use a directive to make a text box automatically grow when it receives focus.
Export keyword – In typescript, each file is considered a module. In each module, often one or more things like a class, function or variable are exported.
Exporting a thing/artefact makes it available in other modules. Later, it can be imported and used.
Now, with all the basic information that we have in hand, we can start creating our very own angular 2 app. Let’s get onto it.
For the initial software setup… go to my next post in this series.