Create Component in Angular 4

Create Component in Angular 4

Type ng g c (Component name like 'home') for Create Component

 

 

CLI automatic update app.module.ts

 

—-Html file (app.component)

Update app-server to app-servers tag.

<app-servers></app-servers>


Create Manual Component

home.component.html

<h1>{{title}}</h1>

home.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {
title="Hello Angular 2"
}

Register Component

app.module.ts

import { HomeComponent } from "./home/home.component";
  declarations: [
    HomeComponent
  ],


Working with Component Templates

Change templateUrl to template in servers.component.ts

—-Ts file (servers.component)

templateUrl: './servers.component.html',

to

template: '<app-server></app-server><app-server></app-server>',

Looks still same here event we remove templateUrl to template.

For multiple Line
For multiple line in our template file. Use ` instead of ‘.

template: '<app-server></app-server><app-server></app-server>',

to

template: `
<app-server></app-server>
<app-server></app-server>`,


Working with Component Styles

Change styleUrls to styles in app.component.ts

—-Ts file (app.component)

styleUrls: ['./app.component.css']

to

//styleUrls: ['./app.component.css']
styles: [`
h1{
color: dodgerblue;
}
`]


Fully Understanding the Component Selector

Selector should be unique every time. Normally selector like this.

—-Ts file (app.servers)

selector: 'app-servers',

Attribute selector

selector: '[app-servers]',

 

—-Html file (app.component)

<div app-servers></div>


Class selector

selector:'.app-servers',

—-Html file (app.component)

<div class="app-servers"></div>

Leave a Reply

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