Developer Snippet Diary

create angular component manually and using CLI, How to add stylesheet

Components are the building blocks that compose an application. 
A component includes a

  1. TypeScript class with a @Component() decorator,
  2. An HTML template, 
  3. styles.

The @Component() decorator specifies the following Angular-specific information:

  1. A CSS selector
  2. HTML template
  3. An optional set of CSS styles that define the appearance of the template's HTML elements

We need an html, and ts file.

1. create app/user/user.component.html

<h1>Hello User</h1>

2. create app/user/user.component.ts , select selector and html file

import { Component } from '@angular/core';
@Component({ //convert class to component
  selector: 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent {
}

3. Register component in app/app.module.ts

import it 

import {UserComponent} from './user/user.component';

add in declarations

declarations: [
    AppComponent, UserComponent
  ],

4. Goto src/app/app.component.html

<div class="container">hello</div>
 <app-user></app-user>

 

Your component will be loaded into app-user tag

 

Create a component using CLI

ng generate component Users

it will create four files , register component, in a folder Users. the .spec file is for testing purpose

Just add this compoenent to your html file.

 

In templateUrl we need to pass the path of html file

In template we can also path the other components

@Component({ //convert class to component
  selector: 'app-user',
  template: '<app-users></app-users>'
})

Stylesheet internal: it will applied to only current component

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styles:[`
    .uw{
      background:blue;
    }
  `],
})

template: to add component 

templateUrl: to add external component ie html

templateUrl: add css to current component

styleUrls: load external css of compoent

selector: 'app-user' , render data inside <app-user></app-user> TAG

selector:['app-user'] render data inside <div app-user></div> ATTRIBUTE

selector:'.app-user' render data inside <div class="app-user"></div>  CLASS

 

Posted by: R GONDAL
Email: rizikmw@gmail.com