Search

An Introduction to Angular Components

Every Application has an important building block, the UI, and a Component in Angular is the basic unit which helps to build a UI. In general user terms UI is referred to as a view. What are Components? Components are basic building blocks which consist of an HTML template that declares what renders on the page, a class written in TypeScript which defines the behaviour, a CSS selector which defines how it can be used in the template and CSS styles which define how it will look when a user views it. Representation of Components:If you’re a programmer by profession and have some fundamental knowledge of user experience, the above diagram will help you to understand about the internal structures of components. Let’s take an example to understand components in a better way, and consider that we are building a page for an application. The features in the page include the header, footer and navigation and content area. Instead of building a single page with all these features, we can choose to split the page into components, which help us to manage our application.In the above scenario, we can say that the header, footer, content area, navigation and so on are separate components of the page; but when the user views it on the website through any device, it will show as a single page.Next, we will find out how to build components, and what is the internal structure of components.The Structure of Components: Components are comprised of Template, Directives and Data bindings. Before creating a component, we should get an idea of what these are. Template - A template combines HTML with Angular mark-up, to modify HTML elements before they are displayed. It’s an HTML file which displays information. Here is an example of a Template: Directives – Directives form an important part of a component. They provide the program logic to the component. Here are some examples of directives: *ngFor, *ngIf Data Binding – Data binding is the process that establishes a connection between the application UI and business logic. Without this, no component in Angular can become functional. Here is an example of Data Binding: ‹div> <span>Current Number is {{value1}}</span> <br><br> <span>Current Number is {{value1 | currency}}</span> <br /><br /> <span>Current Number is {{dt1}}</span> <br /><br /> <span>Current Number is {{dt1 | date}}</span> <br /><br /> <span>Status is {{status}}</span> <br /><br /> </div>Component metadata The metadata for a component tells Angular where to get the major building blocks that it needs to create and present the component and its view. In particular, it associates a template with the component, either directly with inline code, or by reference. Together, the component and its template describe a view. Example of metadata:@Component({  selector:  app-hero-list',  templateUrl:'./hero-list. component. html',  providers:  HeroService  }) Here in the above example, the selector, template URL, and providers consist of metadata which tell where to get the major building blocks.  Next, let us learn how we can configure a component in a project. Configuration of Angular Component The easiest way to create a component is with the Angular CLI. You can also create a component manually.  Creating a component using the Angular CLIFrom a terminal window, navigate to the directory containing your application. Run the ng generate component <component-name> command, where <component-name> is the name of your new component. By default, this command creates the following: A folder named after the component A component file, <component-name>.component.ts A template file, <component-name>.component.html A CSS file, <component-name>.component.css A testing specification file, <component-name>.component.spec.ts Where <component-name> is the name of your component. Creating a component manually Navigate to your Angular project directory. Create a new file, <component-name>.component.ts. At the top of the file, add the following import statement. import { Component } from '@angular/core'; After the import statement, add a @Component decorator. @Component({  }) Choose a CSS selector for the component. @Component({   selector: 'app-component-overview',  }) Define the HTML template that the component uses to display information. In most cases, this template is a separate HTML file. @Component({  selector: 'app-component-overview',   templateUrl: './component-overview.component.html',  }) Select the styles for the component's template. In most cases, you define the styles for your component's template in a separate file. @Component({   selector: 'app-component-overview',  templateUrl: './component-overview.component.html',  styleUrls: ['./component-overview.component.css']  }) Add a class statement that includes the code for the component. export class Component Overview Component {  } For more details information on creating an Angular component, the reader can go through the official website of Angular refWe are now going to learn another concept in terms of the uses of Angular components. Let’s talk about the use of Aliases for importing components. Aliases in Angular component imports  When working with Angular projects in real time, we might come across a scenario where we are required to remember a long relative path for a component in an Angular file. This often proves to be difficult, and it makes the application messy and complex to read, especially if you are new to the team. This is where Aliases come to the rescue. You might come across something like:In the above example, we should use aliases for relative paths to improve the readability of the code. To achieve this in your Angular application, all you need to do is to update the tsconfig.json file. If you look at the above configuration, the default property of the baseUrl property was updated to ‘src’ directory. Then, we added a new property called paths, which is an object containing key-value pairs representing aliases defined for the paths in our application. The above code can be rewritten as shown below: Like Aliases help in code readability, Lazy load is also a very useful Angular feature. Let’s Understand Lazy Load in terms of any programming language: As the term itself suggests, a Lazy Load is loaded late and only when needed. To understand this in a better way, consider a VIEW MORE button on any web page of an application. When we click on this VIEW MORE button, it loads the rest of the content and displays it to the user. In a similar way, in Angular applications, we have several such components which are not very important. Only when the user wants to view these components, they must be loaded. We use Lazy load in such scenarios, as using this feature will make the best use of time and space in applications. There are two main steps to setting up a lazy-loaded feature module: Create the feature module with the CLI, using the --route flag. Configure the routes. To understand in more detail, with some sample code, please go through this reference URL where it is explained very well by the Angular TeamIn the example below, the LOAD MORE Button is created using the lazy loading concept. Visitors can view more blogs only if they are interested by clicking on this button.Conclusion: I hope this blog will help readers to understand some basic concepts of Angular components and their structure. To explore more advanced concepts and delve deeper into Angular 2-11,  visit this link.
An Introduction to Angular Components
Jaya
Jaya

Jaya Jha

Author

I am a full-stack Web Application Developer and passionate about exploring cutting edge technologies. I love to write technical blogs.

Posts by Jaya Jha

An Introduction to Angular Components

Every Application has an important building block, the UI, and a Component in Angular is the basic unit which helps to build a UI. In general user terms UI is referred to as a view. What are Components? Components are basic building blocks which consist of an HTML template that declares what renders on the page, a class written in TypeScript which defines the behaviour, a CSS selector which defines how it can be used in the template and CSS styles which define how it will look when a user views it. Representation of Components:If you’re a programmer by profession and have some fundamental knowledge of user experience, the above diagram will help you to understand about the internal structures of components. Let’s take an example to understand components in a better way, and consider that we are building a page for an application. The features in the page include the header, footer and navigation and content area. Instead of building a single page with all these features, we can choose to split the page into components, which help us to manage our application.In the above scenario, we can say that the header, footer, content area, navigation and so on are separate components of the page; but when the user views it on the website through any device, it will show as a single page.Next, we will find out how to build components, and what is the internal structure of components.The Structure of Components: Components are comprised of Template, Directives and Data bindings. Before creating a component, we should get an idea of what these are. Template - A template combines HTML with Angular mark-up, to modify HTML elements before they are displayed. It’s an HTML file which displays information. Here is an example of a Template: Directives – Directives form an important part of a component. They provide the program logic to the component. Here are some examples of directives: *ngFor, *ngIf Data Binding – Data binding is the process that establishes a connection between the application UI and business logic. Without this, no component in Angular can become functional. Here is an example of Data Binding: ‹div> Current Number is {{value1}} Current Number is {{value1 | currency}} Current Number is {{dt1}} Current Number is {{dt1 | date}} Status is {{status}} Component metadata The metadata for a component tells Angular where to get the major building blocks that it needs to create and present the component and its view. In particular, it associates a template with the component, either directly with inline code, or by reference. Together, the component and its template describe a view. Example of metadata:@Component({  selector:  app-hero-list',  templateUrl:'./hero-list. component. html',  providers:  HeroService  }) Here in the above example, the selector, template URL, and providers consist of metadata which tell where to get the major building blocks.  Next, let us learn how we can configure a component in a project. Configuration of Angular Component The easiest way to create a component is with the Angular CLI. You can also create a component manually.  Creating a component using the Angular CLIFrom a terminal window, navigate to the directory containing your application. Run the ng generate component  command, where  is the name of your new component. By default, this command creates the following: A folder named after the component A component file, .component.ts A template file, .component.html A CSS file, .component.css A testing specification file, .component.spec.ts Where  is the name of your component. Creating a component manually Navigate to your Angular project directory. Create a new file, .component.ts. At the top of the file, add the following import statement. import { Component } from '@angular/core'; After the import statement, add a @Component decorator. @Component({  }) Choose a CSS selector for the component. @Component({   selector: 'app-component-overview',  }) Define the HTML template that the component uses to display information. In most cases, this template is a separate HTML file. @Component({  selector: 'app-component-overview',   templateUrl: './component-overview.component.html',  }) Select the styles for the component's template. In most cases, you define the styles for your component's template in a separate file. @Component({   selector: 'app-component-overview',  templateUrl: './component-overview.component.html',  styleUrls: ['./component-overview.component.css']  }) Add a class statement that includes the code for the component. export class Component Overview Component {  } For more details information on creating an Angular component, the reader can go through the official website of Angular refWe are now going to learn another concept in terms of the uses of Angular components. Let’s talk about the use of Aliases for importing components. Aliases in Angular component imports  When working with Angular projects in real time, we might come across a scenario where we are required to remember a long relative path for a component in an Angular file. This often proves to be difficult, and it makes the application messy and complex to read, especially if you are new to the team. This is where Aliases come to the rescue. You might come across something like:In the above example, we should use aliases for relative paths to improve the readability of the code. To achieve this in your Angular application, all you need to do is to update the tsconfig.json file. If you look at the above configuration, the default property of the baseUrl property was updated to ‘src’ directory. Then, we added a new property called paths, which is an object containing key-value pairs representing aliases defined for the paths in our application. The above code can be rewritten as shown below: Like Aliases help in code readability, Lazy load is also a very useful Angular feature. Let’s Understand Lazy Load in terms of any programming language: As the term itself suggests, a Lazy Load is loaded late and only when needed. To understand this in a better way, consider a VIEW MORE button on any web page of an application. When we click on this VIEW MORE button, it loads the rest of the content and displays it to the user. In a similar way, in Angular applications, we have several such components which are not very important. Only when the user wants to view these components, they must be loaded. We use Lazy load in such scenarios, as using this feature will make the best use of time and space in applications. There are two main steps to setting up a lazy-loaded feature module: Create the feature module with the CLI, using the --route flag. Configure the routes. To understand in more detail, with some sample code, please go through this reference URL where it is explained very well by the Angular TeamIn the example below, the LOAD MORE Button is created using the lazy loading concept. Visitors can view more blogs only if they are interested by clicking on this button.Conclusion: I hope this blog will help readers to understand some basic concepts of Angular components and their structure. To explore more advanced concepts and delve deeper into Angular 2-11,  visit this link.
9265
An Introduction to Angular Components

Every Application has an important building block,... Read More

React vs Angular: An In-depth Comparison

There is lot of buzz in the market about Angular and React. You might have come across these two front-end technology stacks, irrespective of whether you are an experienced professional or a beginner in the field of programming. A question that may plague most of you is---which of these two is the better technology to master, in terms of a career and which one is easier? Being a full stack developer, I will try to explain in-depth the difference between the two, based on my personal experience.So, let’s start right at the beginning and understand what React and Angular are: -React – In simple terms React is a JavaScript library for building interactive user interfaces. It is maintained by Facebook and a community of individual developers and companies.Angular – Angular is a JavaScript framework for web application development, led by the Angular Team at Google and by a community of individuals and corporations.Let’s first understand these two terms: JavaScript Library and JavaScript framework.   Consider a scenario of writing a hide and show functionality on a web page for a simple div and the amount of code we have to write for the same. Using a JavaScript library as jQuery we can use inbuilt functions like hide() and show() and complete the number of lines of work by simply using a function.To learn more about jQuery, please go through the official site at this link.So, in other words, a library has a set of defined functions which will help us to design interactive front-end applications easily, whereas JavaScript framework is a collection of such libraries which has tons of inbuilt functions which speed up our website development.  React being a JavaScript library has inbuilt functions, but Angular being a Framework has a collection of inbuilt functions. So, when it comes to inbuilt functions, Angular gives us a wide range of options. Now let’s try and understand the difference between React and Angular:Technical ConsiderationsAngularReactJavaScriptFrameworkLibraryDocument Object ModelReal DOM – DOM organizes the HTML documents in the form of a tree. In Angular, Real DOM is used which means the whole tree structure is refreshed when a single change is made. This makes the process slower.Virtual DOM – With this you can change any element very quickly and without needing to render the whole DOM. It drastically changes the performance from good to excellent.Programming LanguageTypeScriptJavaScriptTemplateTypescript inside HTMLHTML inside JavaScriptData BindingTwo-way- In which model state changes automatically when any change in UI element is made, and vice-versa.One-way- In which the UI elements can be changed only after changing the model state. The developers cannot alter the UI elements without updating the corresponding model state.PerformanceBecause of real DOM it is slow compared to ReactAs React uses virtual DOM, it is faster than AngularTypes of AppsUsing Angular we can build large complex Enterprise applications, Single Page applications, as well as Mobile ApplicationsSmall Applications, Native mobile applicationsThese are the key differences between these two technology stacks. If you wish to dig deeper, you can find more differences over the internet. So are you planning to master either of these two? You can, but there are certain prerequisites you should know before you get started.Angular – As Angular is a JavaScript framework basically written in TypeScript, one should be well versed with JavaScript basics as well as advance concepts. Without knowing TypeScript, it is difficult to master Angular.Generally, for Angular based applications Testing and Debugging are possible with a single Tool. Whereas for React applications, we have to use various sets of tools for Debugging and Testing.React – React, on the other hand, is a much easier library to master than Angular. Anyone who knows the basics of JavaScript syntax and HTML syntax can learn React.JSX – Is an XML-like language that allows you to write mark-up directly in your JavaScript code. React decided to combine them within components using JSX. JSX syntax is like writing HTML inside JavaScript, so if you know the basics of JavaScript and HTML it becomes easier for you.Being a developer, I always love to understand concepts using sample code snippets. Here are some code snippets, to help you understand these technology stacks better.React Sample Code for Hello World:It’s basically a standard JavaScript class which returns HTML. With React components we import React at the top using a standard JavaScript import statement and then declare a component using a standard JavaScript class.   The syntax you see above inside the render () function is JSX which simply compiles to JS. This is the most basic React code for a developer to start with, as it is a simple JavaScript function and is easy to understand.Angular Sample Code for Hello World:Above is a simple Angular component file which is written in TypeScript where @Component defines the metadata of component. The selector is the custom HTML name we’ll use to include this component. We’ll add a message variable inside of the demo component class and define its type as a string. Inside the ngOnInit method, we’ll give it a default value. ngOnInit is a life cycle method that executes before the component is mounted. We can also use the constructor for this purpose, as they will both give the same result for this application.Next, we have created the HTML, where we are using an H1 tag to display the current value of the message variable. The double braces are used to interpolate the value of the message. We’ll also create a form without an action, which consists of a label and an input field of type text. To create a two-way binding, we need to use ngModel which will allow us to change the value of the message variable and then the name property will display the value of the variable inside of the input field. So, before we type anything, it should have the default value “Hello” written into it.  Once we include this component inside our main component and run the application, we will see the output as Hello. This is an example of Two-way Data Binding, since changing the input immediately reflects on the browser.I have written these two-sample codes to explain the approach of React and Angular. Notice how the different coding styles can help differentiate between the code written in Angular and React. For a beginner or experienced programmer, it is important to get the hang of the coding style of a particular language to develop expertise in it.Till now we have seen the technical differences of Angular and React. But to understand which technology stack to pursue it is important to gauge your interest in the particular framework or language and its popularity in the real world.  In other words, understand which companies are using that technology. Let’s now look at who around the world is using React and Angular.FACEBOOK – The tech giant Facebook is the founder of React and majorly uses React components in Facebook, which is one of the highest traffic sites. Similarly, it is used in WhatsApp and Instagram which has an even larger user base. GOOGLE – Google is the founder of Angular. It uses Angular in several of its internal projects, as well as in many customer projects because of its MVC Architecture. Sitecore - is a customer experience management company that provides web content management and multichannel marketing automation software. It has a complete Sitecore JavaScript Services SDK for JavaScript developers that enables building full -fledged solutions using modern JavaScript UI libraries like React and Frameworks like Angular. This helps us gauge the popularity of React and Angular. Facebook and Google are just two of the most popular companies using these technologies. There are several enterprises around the world that have adopted and benefited from React and Angular. So, now that you know that both are equally popular, let us try and understand which one of the two is easier to learn.Since to learn anything it is important to have a solid foundation, the easier technology to learn would be the one where the prerequisites to learn it are easier. Another important factor is Community Support which is very important when it comes to learning a new technology. A growing and active community plays a major role is helping one master a technology stack.Learning CurveReact – Personally I feel learning React is easy as it is based on JavaScript. If we are well versed in advanced JavaScript concepts, we can do very well in React. If you want to explore the ways to get started with React, please go through these listed resources which are very useful for a beginner: Angular – The learning curve for Angular is steeper than React, as Angular is a complex and verbose framework. TypeScript may look similar to JavaScript but takes a little longer to learn.  Beginners should always start with what is easier, and then gradually move towards complex code, so it makes sense to start learning React first and then get into Angular.I am going to list a few blogs as references, which I think are wonderful resources in the journey of exploring and learning Angular and its concepts. Community Support & UpdatesAngular releases newer versions or updates every six months. So, in a year, there are two major releases or updates to make necessary changes. Developers have experienced many changes since its release and the current version is version 10.  Angular is supported by huge and active communities of Google.React is maintained by Facebook and its current version is 16.13.1. Upgrades in React are easier than in Angular. Also, stability is a major concern when it comes to releasing newer versions of React, since big companies like Twitter and Airbnb use it. It also has good community support.MigrationUpdates and Migration are also important aspects of any project created in React or Angular. React projects are easy to migrate and update as Facebook developers give regular updates along with breaking changes updates.With migration projects, we can migrate one part of a page component wise. This ensures that there are no breaks in the other functionalities of a working project. Because of this feature, Facebook has been successful in migrating many of its pages into React components.Whereas, Angular is not that easy to migrate, as a lot of its libraries have to be used in a single project and because of its two-way binding it is connected to modal state as well. Angular projects are large and complex, and it takes proper planning and timelines to migrate full projects.When you are migrating your project, there may be a need to add some React code to the site. To learn more about how you would do this, read. Let’s see the latest Google Trends to compare the popularity of Angular and React along with stack overflow Trends. Google Trends: Image SourceStack Overflow:Image SourceThe above graph gives you an idea of the presence and popularity of React and Angular in the present market. React leads the race because of its simple and easy syntax that makes it more appealing to beginners and companies who are adopting it for small projects. But Angular also has its own unique features which are being used by lots of developers for enterprise level applications. Conclusion  Through this post I have tried to explain some important aspects of React and Angular and the differences between the two. I would recommend that those who wish to master these two technologies, go through the official documentation of Angular and React as it explains a lot of concepts and components in a detailed manner. Going through the official documentation is always a great option to learn any new technology and follow along. At the end I am listing out the links of official sites for learning resources of Angular and React. I am also going to list out a few references of important concepts of React and Angular which are very important for a beginner to start with. 
5655
React vs Angular: An In-depth Comparison

There is lot of buzz in the market about Angular a... Read More