Know about Angular Components and How to Create Nested Components in Angular?
In the previous article about Angular, we covered What are Pipes in Angular and how to create custom pipes?. Now, in this article, we will learn about Angular components and we will also see how to create a nested component and how parent and child components communicate with each other.
Angular Components
We all know that Angular is a component-based framework because everything is a component in Angular. Basically, components are the basic building blocks of Angular application. It also allows us to create reusable UI templates.
A component in Angular is a class with a template and a decorator. There are basically the following parts of Angular component –
- Class
It is very similar to the C# class or java class etc. It contains the constructor, variables and methods code which is required for the template/user interface.
- Decorator
A decorator is used to store the metadata about the class. Basically, the decorator provided by Angular makes a class an Angular component when it is decorated with the component decorator.
Angular provides us basically 4 types of decorators,
- Class Decorators
For Ex. @NgModule, @Component & @Directive
- Property Decorators
For Ex. @Input & @Output
- Method Decorators
For Ex. @HostListener
- Parameter Decorators
For Ex. @Inject
I am not going to define the types of decorators here in detail. We will discuss in detail about them in later articles.
Each decorator has a basic configuration using several properties. We are taking a look at some possible configuration properties right here, that you can use when creating a component,
- Selector – This is used for identifying this component in templates.
- Template – This is used for defining HTML template inline for the view.
- TemplateUrl – This is used for defining a URL to an external file containing a template for the view.
- Styles – This is used for defining inline CSS to be applied to the template of this component.
- StyleUrls – This is used for defining URLs to external style sheets to be applied to the templates of this component.
- viewProviders – This is used for defining a list of providers available for this component and its view children
For all configurations, click here.
Let’s understand the component and its parts with the help of below screenshot and component code.
This shows where the decorators are actually applied to a class and how they are actually responsible for making a class an Angular component.
This shows where the decorators are actually applied to a class and how they are actually responsible for making a class an Angular component.
App.component.ts
- import { Component } from '@angular/core';
- @Component({
- selector: 'my-app',
- template: `<list-student></list-student>`,
- })
- export class AppComponent {
- name = 'Angular';
- }
Nested Components
Now, we will look how to create a nested component (parent component and child component) in Angular applications and how parent and child components will communicate with each other.
I am using the same student project which I have been using in my previous articles so far. You can download it from here. We will create search bar component and search functionality for the existing student list component.
Let’s understand it with the following steps –
Since we want to make search-bar component as a shared component, we will keep related files in a new folder i.e. shared/searchbar.
Step 1. Add the search bar component TypeScript file
Add a new folder named “Shared” inside app folder and create another folder “SearchBar” inside this “Shared” folder to add the component files. And now, create a TypeScript file “searchbar.component.ts” under this “SearchBar” folder.
Add the below code into the “searchbar.component.ts” file.
Add the below code into the “searchbar.component.ts” file.
searchbar.component.ts
- import { Component, Output, EventEmitter } from '@angular/core'
- @Component({
- selector: 'search-bar',
- templateUrl: 'searchbar.component.html',
- moduleId: module.id
- })
- export class SearchBarComponent {
- @Output()
- Search = new EventEmitter<string>();
- OnStudentSearch(searchTerm:string): void {
- this.Search.emit(searchTerm);
- }
- }
In the above code, we imported two components, Output and EventEmitter, from Angular core module. With the help of these two, we will inform the parent component when OnStudentSearch method will be called. We created a custom event “Search” which will emit when OnStudentSearch method will be called, so parent component will know about the event. The emit function has been used to fire this custom event.
We have mentioned the search bar template URL in templateUrl property, which we will create in a little bit.
Step 2. Add the search bar template file
Add an html searchbar.component.html file inside the same app -> Shared -> “SearchBar” folder and add the below code into this file,
- <div class="form-group">
- <div class="md-col-4">
- <label>Enter Student Name:</label>
- </div>
- <div class="md-col-4">
- <input class="form-control" #searchInput type="text" />
- </div>
- </div>
- <button type="submit" class="btn btn-default" (click)="OnStudentSearch(searchInput.value)">
- Search
- </button>
Now our searchbar component is complete to nest inside the existing StudentList component.
Step 3. Nest the SearchBar component inside the StudentList component
Open the existing student.component.html file from app -> student folder and added the below code as highlighted,
- <search-bar (Search)="OnStudentSearch($event)"></search-bar>
- <table class="table table-responsive table-bordered table-striped">
- <thead>
- <tr>
- <th>Student ID</th>
- <th>Name</th>
- <th>Gender</th>
- <th>Age</th>
- <th>Course</th>
- <th>DOB</th>
- <th>Grade</th>
- <th>Rating</th>
- </tr>
- </thead>
- <tbody>
- <tr *ngFor="let s of students;">
- <td>{{s.studentID}}</td>
- <td>{{s.studentName | uppercase}}</td>
- <td>{{s.gender | lowercase}}</td>
- <td>{{s.age}}</td>
- <td>{{s.course | courseCategory}}</td>
- <td>{{s.DOB | date:'yMMMMd' | uppercase }}</td>
- <td>{{s.grade | percent:'.2'}}</td>
- <td>{{s.rating | number:'2.1-2'}}</td>
- </tr>
- </tbody>
- </table>
In the above code, you can see how it has been nested with the StudentList component. This is how we can create nested component in Angular.
Step 4. Update StudentList component for search functionality
To filter the student list, we will update the LoadStudents method which will provide us the result after filtering the students with the help of search term passed from child component i.e. SearchBar component. Take a look at the code highlighted below.
- import { Component, OnInit} from '@angular/core'
- @Component({
- selector: 'list-student',
- templateUrl: 'app/student/student.component.html'
- })
- export class StudentListComponent implements OnInit {
- students: any[];
- public LoadStudents(filterText: string): void {
- this.students = [
- { studentID: 1, studentName: 'Steve', gender: 'Male', age: 35, course: 'MCA', DOB: '10/12/1982', grade:0.7500,rating:7.5123 },
- { studentID: 2, studentName: 'Bobby', gender: 'Male', age: 32, course: 'MBA', DOB: '12/1/1985', grade: 0.7850, rating: 7.8223 },
- { studentID: 3, studentName: 'Rina', gender: 'Female', age: 45, course: 'B.Tech', DOB: '9/11/1972', grade: 0.8525, rating: 8.5263 },
- { studentID: 4, studentName: 'Alex', gender: 'Female', age: 24, course: 'M.Tech', DOB: '1/1/1993', grade: 0.5540, rating: 5.5123 },
- { studentID: 5, studentName: 'Rahul', gender: 'Male', age: 26, course: 'MCA', DOB: '1/21/1991', grade: 0.9550, rating: 9.5534 },
- ];
- if (filterText != "") {
- var filterStudentList: any[] = [];
- this.students.forEach(stu => {
- if (stu.studentName.toLowerCase().includes(filterText)) {
- filterStudentList.push(stu);
- }
- })
- this.students = filterStudentList;
- }
- }
- ngOnInit() {
- this.LoadStudents("");
- }
- OnStudentSearch(searchTerm: string): void {
- this.LoadStudents(searchTerm);
- }
- }
Step 5. Register the SearchBar component in Angular app module
Now, we will include our SearchBar component in the Angular app module. Add the code as highlighted below.
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { AppComponent } from './app.component';
- import { StudentListComponent } from './student/student.component'
- import { courseCategoryPipe } from './student/student.coursepipe'
- import { SearchBarComponent } from './Shared/SearchBar/searchbar.component'
- @NgModule({
- imports: [BrowserModule],
- declarations: [AppComponent, StudentListComponent, courseCategoryPipe, SearchBarComponent],
- bootstrap: [ AppComponent ]
- })
- export class AppModule { }
Step 6. Now, run the application to get the expected result
Run the application using F5 or Ctrl + F5 and see the search bar as expected in the browser.
Output
Let’s take a look at search functionality. Let’s enter the term “Rahul” in the search box and hit the "Search" button to get the student list.
Let’s take a look at search functionality. Let’s enter the term “Rahul” in the search box and hit the "Search" button to get the student list.
Output on filter
Summary
Summary
In this article, we covered the following topics.
- What is a component in Angular and what are the main parts of Angular component?
- What are decorators and what are the types of a decorator in Angular?
- What are the configuration properties of a decorator in Angular 2?
- What is a nested component in Angular and how parent and child components communicate with each other?
To read more articles on Angular, please check out the below links,
- How to setup Angular with TypeScript in Visual Studio 2015
- Learn Angular *ngFor Directive with trackBy and other local variables
Write to me in the comment box in case you need any help or you have any questions or concerns. Have a good day!
Thanks for sharing this angularjs components.
ReplyDeleteAngularjs Training | Angular 2 Training in Chennai | Angularjs Training in Chennai
Useful post, share more like this.
ReplyDeleteReact js Training in Chennai | React js Training
Pretty! This was a really wonderful post. Thank you for providing these details.
ReplyDeleteAngularjs Training in Bangalore , Angular 2 Training in bangalore , Python Training in Bangalore
Really very nice blog information for this one and more technical skills are improve,i like that kind of post.
ReplyDeleteTechnology
oceanofquotes
Given article is useful and informative.The article shared more informations about Angular Js training for further reference refer Angular training in kochi and Angular course in kochi
ReplyDeletenice post with a lot of valuable and unique information.
ReplyDeleteAngularJS training in chennai | AngularJS training in anna nagar | AngularJS training in omr | AngularJS training in porur | AngularJS training in tambaram | AngularJS training in velachery
Hi, A very nice guide to know the component about angular explained clearly.I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you blog.
ReplyDeleteDevOps Training in Chennai
DevOps Online Training in Chennai
DevOps Training in Bangalore
DevOps Training in Hyderabad
DevOps Training in Coimbatore
DevOps Training
DevOps Online Training
Well Said,JAVA interface you have provided the right info that will be beneficial to somebody at all time. keep up!!
ReplyDeleteJava training in Chennai
Java Online training in Chennai
Java Course in Chennai
Best JAVA Training Institutes in Chennai
Java training in Bangalore
Java training in Hyderabad
Java Training in Coimbatore
Java Training
Java Online Training
Thank you for the information. It is very useful and informative
ReplyDeleteangular js course in chennai
angular course in chennai
angular js online course in chennai
angular js course in bangalore
angular js course in hyderabad
angular js course in coimbatore
angular js course
angular js online course
Really very nice blog information for this one and more technical skills are improve,i like that kind of post.
ReplyDeleteAWS Course in Chennai
AWS Course in Bangalore
AWS Course in Hyderabad
AWS Course in Coimbatore
AWS Course
AWS Certification Course
AWS Certification Training
AWS Online Training
AWS Training
Pretty! This was a really wonderful post. Thank you for providing these details.
ReplyDeleteacte chennai
acte complaints
acte reviews
acte trainer complaints
acte trainer reviews
acte velachery reviews complaints
acte tambaram reviews complaints
acte anna nagar reviews complaints
acte porur reviews complaints
acte omr reviews complaints
Commercial awareness (or business acumen) This is about knowing how a business or industry works and what makes a company tick..keep share more information!!!
ReplyDeleteAndroid Training in Chennai
Android Online Training in Chennai
Android Training in Bangalore
Android Training in Hyderabad
Android Training in Coimbatore
Android Training
Android Online Training
Its a great pleasure reading your post.Its full of information
ReplyDeleteCyber Security Training Course in Chennai | Certification | Cyber Security Online Training Course | Ethical Hacking Training Course in Chennai | Certification | Ethical Hacking Online Training Course | CCNA Training Course in Chennai | Certification | CCNA Online Training Course | RPA Robotic Process Automation Training Course in Chennai | Certification | RPA Training Course Chennai | SEO Training in Chennai | Certification | SEO Online Training Course