Sunday, 25 October 2020

Angular - Nested Components Angular

Figure 1


 Adding a component to another component is Nested Components in Angular. 

From Figure 1, 

  • EmployeeDetails header should come from AppComponent 
  • And the below table contains employee Details should come from another component.

3 steps need to be followed to achieve this.

Step 1:

  • Create a new folder employeecomponent and add below files inside 
    • EmployeeComponent.ts
    • app.EmployeeComponent.html 
                    
Folder structure after adding files

Step 2:

Add below changes in the newly added files
    • EmployeeComponent.ts
    • import { Component } from "@angular/core";
      @Component(
          {
              selector:'Employees',
              templateUrl:'app.EmployeeComponent.html'  
          }
      )
      export class EmployeeComponent
      {
          FirstName : string = "Angular";
          LastName : string = "Tutorial";
      }
    • app.EmployeeComponent.html 
    • <table border="1px">
          <tr>
              <td>FirstName</td>
              <td>{{FirstName}}</td>
          </tr>
          <tr>
              <td>LastName</td>
              <td>{{LastName}}</td>
          </tr>
      </table>

Step 3:

Import the component in app.module.ts and add EmployeeComponent in declaration as below and compile and Run the application. We will get the desired output as seen at the top

import { EmployeeComponent } from "./employeecomponent/EmployeeComponent";

@NgModule({
  declarations: [
    AppComponent,     
    EmployeeComponent
  ],
........
........
})

Angular - template Vs templateUrl

import { Component } from "@angular/core";

@Component({selector:'my-App',
            template:`<h1>{{name}}</h1>`,
            templateUrl:'app.component.html'
})
export class AppComponent
{
  name : string = "name";} 


template and templateUrl can be used inside the decorator.

template:

  • When a template view content is very less, template property can be used.
  • This content can be present inside single/double quotes or backtick characters as displayed in the sample code.
  • Single/double quotes can be used whenever the content is in a single line
  • If the template view content has more than a line then, it is mandatory to use backtick character

DisAdvantages

  • Intellisense and formatting can't be done using Visual Studio / VS Code
  • Hard to read when Typescript and HTML are present together if HTML content is more

Example:

  • template:`<h1>{{name}}</h1>`,

templateUrl:

  • The external HTML file can be referred to when the content is more as referred in an initial screenshot
  • It provides better readability, Intellisense and formatting the content

Example:

  • templateUrl:'app.component.html'


How Angular Applications are Boot strapped

 How Angular application is Bootstrapped? Angular applications are single-page applications. Only one HTML file will be available. only the ...