What we know?
- Angular is component based framework which is comprised of TypeScript and JavaScript
- TypeScript is superset of JavaScript
- As JavaScript is subset of TypeScript, so every JavaScript code is a valid TypeScript code
- TypeScript has some addon features as extended to JavaScript
– Why TypeScript in Angular?
TypeScript is choosen because of its most rich feature of type checking and autocompletion. Some other features mentioned below:
- Consistency
- Productivity
- Maintainability
- Modularity
- Catch Errors Early
more you can read here on it’s official documentation. This made Angular super-awesome 👍. If you know languages like C# or Java, then it is pretty simple to get into it with the help of documentation. To start with Angular, you don’t need to deep dive into it, just an overview of it and basic OOP concept will work. Get the complete understanding for TypeScript on their site by firstly learning the basic types and then by quick overview.
– What is a Component?
As we see above that Angular is a component based framework. Each single component again contains 3 elements:
- HTML (.html) – this creates view, i.e. markup code
- TS (.ts) – where all your business logic goes
- CSS (.css) – here you can do styling for the markup. It can be CSS/SCSS, etc.
Now, focusing towards our TS element of component i.e. .ts file, lets break down this component to get a clear idea about it.
we can divide structure of component in following 4 parts:
1. import statements:
import statements imports all the required classes from the module packages which is required for the component and methods[in your logic]. Example can be seen below:
2. @Component():
Component is a method, not a normal method, ‘@’ symbol makes it a decorator, a component decorator. This decorator provides configuration metadata of the component. It takes an object as an parameter. Example can be seen below:
Here, selector, templateUrl and styleUrls are the properties of the component. There are many more properties we can use as per convenience.
3. export class:
As a framework, Angular provides modular structure. So all the components used in the application are a exported class. So whenever we need to export or reuse it we can easily import it in any module and implement in that another component. Example given below:
Each component class can have constructor as shown in the above image. Below constructor we have ngOnInit() function which is first stage of lifecycle hook of the angular component. Then you go with your user define functions as you want your component should act or to be functioned.