Sunday, 3 November 2019

What is selector in Component?


In any component selector contains an element which make the component reusable. By using the selector element, we can call the component as a html tag in any other components view template.
There three way to define selector

·       As an element
·       As a style class
·       As an attribute

Below is the example which demonstrates all possible ways

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

@Component({
  selector  'app-server',
  templateUrl  './server.component.html',
  styleUrls  ['./server.component.css']
})
export class ServerComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

<div class="contaner">
    <div class="row">
        <div class="col-xs-12">
            <h3>Server Details</h3>
            <hr>
        </div>
    </div>
    <app-servers></app-servers>
</div>

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

@Component({
  selector  '[app-servers]',
  templateUrl  './servers.component.html',
  styleUrls  ['./servers.component.css']
})
export class ServersComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


<div class="contaner">
    <div class="row">
        <div class="col-xs-12">
            <h3>Server Details</h3>
            <hr>
        </div>
    </div>
    <!-- <app-servers></app-servers> -->
    <div app-servers></div>
</div>



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

@Component({
  //selector  'app-servers',  --- As element
  //selector  '[app-servers]',  --- As Attribute
  selector  '.app-servers',    // As Class
  templateUrl  './servers.component.html',
  styleUrls  ['./servers.component.css']
})

export class ServersComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


<div class="contaner">
    <div class="row">
        <div class="col-xs-12">
            <h3>Server Details</h3>
            <hr>
        </div>
    </div>
    <!-- <app-servers></app-servers> -->
    <!-- <div app-servers></div> -->
    <div class="app-servers"></div>
</div>

5 comments: