Tuesday, August 10, 2021

Angular Component Selectors

A decorator is used to mark the class as the component in Angular, and it provides informational metadata that defines what kind of properties can be used by the existing component.


A component takes properties as metadata as object, and the object contains key-value pairs like selector, style, or styleUrl. All these properties make a component a complete reusable chunk for the Angular application.


A selector is one of the properties of the object that we use along with the component configuration.


A selector is used to identify each component uniquely into the component tree, and it also defines how the current component is represented in the HTML DOM.


When we create a new component using Angular CLI, the newly created component looks like this.


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


@Component({

  selector: 'my-app',

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

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

})

export class AppComponent  {

  name = 'This is simple component';

}


Here in app.component.ts, notice that we have one property called selector along with the unique name used to identify the app component in the HTML DOM tree once it is rendered into the browser.


 <my-app> is rendered initially because the app component is the root component for our application. If we have any child components, then they all are rendered inside the parent selector.


Basically, the selector property of the component is just a string that is used to identify the component or an element in the DOM.


By default, the selector name may have an app as a prefix at the time of component creation, but we can update it. Keep in mind that two or more component selectors must not be the same.



Selector as an Attribute



We have looked at an example of how to use a selector as an element name, but we are not limited to that. We can also use a selector as an attribute of an element, just like we do along with other HTML elements.

@Component({

4  selector: '[my-app]',

5  templateUrl: './app.component.html',

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

7})



Selector as a Class



@Component({

4  selector: '.my-app',

5  templateUrl: './app.component.html',

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

7})

8export class AppComponent  {

9  name = 'Angular';

10}







References

https://www.pluralsight.com/guides/understanding-the-purpose-and-use-of-the-selector-in-angular

No comments:

Post a Comment