Nested Component in Angular2?

Nested Component in Angular2?

Nested component means a component under another component. Just to iterate what I discussed in my early post , component is a class with a template and  decorator/metadata.

However, if you want to know more details about component then please visit my previous post –  https://indianjackofalltrade.com/what-is-components-in-angular2

Hence, we will create below tables with nested component approach. As you can see we can divide the form in two parts, one is header and another one is table.  First of all we will see how to create table header then its contents, after that we will connect both as nested component.

Student Details

1. Modify app.component.ts code with below code –

import {Component} from “@angular/core”;

@Component({

selector:”kris-app1″,

templateUrl:’app.component.html’

})

export class AppComponent{

pageHeader: string = “Student Details”;

}

 

 

app.component.ts

2. Append below code in file app.component.html.

<div>

<H1>{{pageHeader}}</H1>

</div>

app.coponent.html

3. Then run the code. The output will be like below screenshot. So, our header is ready.

Student Details 2

4. Now we have to create table and its content. Under ‘App’ folder in the project directory create a folder named ‘Students’ and then under that create two files i.e. student. component.html and student. component.ts

<table>

<tr>

<td>First Name</td>

<td>{{firstName}}</td>

</tr>

<tr>

<td>Last Name</td>

<td>{{lastName}}</td>

</tr>

<tr>

<td>Location</td>

<td>{{location}}</td>

</tr>

<tr>

<td>Age</td>

<td>{{age}}</td>

</tr>

</table>

Student.component.html

5. Add below code to student.component.ts file –

import {Component} from “@angular/core”

@Component({

selector :’my-students’,

templateUrl: ‘student.component.html’

})

 

export class StudentsComponent {

firstName:string= “krishnan”;

lastName:string=”banerjee”;

location:string=”India”;

age:number=24;

}

student.component.ts

6. Our student component is ready and as well as Header component also. Now a connection need to establish to make it nested.

7. Append selector <my-student></my-student> to  the file app.component.html

app.component.html

8. Modify file ‘app.module.ts’ file with below marked code . This file was created during project creation –

import { BrowserModule } from ‘@angular/platform-browser’;

import { NgModule } from ‘@angular/core’;

import { AppComponent } from ‘./app.component’;

import { StudentsComponent } from ‘./students/student.component’;

@NgModule({

declarations: [

AppComponent,

StudentsComponent

],

imports: [

BrowserModule

],

providers: [],

bootstrap: [AppComponent]

})

export class AppModule { }

app.module.ts

 

One Reply to “Nested Component in Angular2?”

Leave a Reply

Your email address will not be published. Required fields are marked *