Angular 13 selectors

Angular 13 provides the core @Component
decorator to make components out of typescript classes. This decorator takes an object as an argument, which includes a set of attributes. In Angular, a decorator is used to designate a class as a component and to supply additional metadata defining which features may be accessed by the underlying component.
An Angular decorator is a class that serves as a marker for a component and provides extra information about the underlying component's capabilities, such as which features are accessible.
The component’s decorator accepts attributes as metadata, and the object comprises key-value pairs such as selector, style, or styleUrl. All of these attributes may be used together to create a from component’s class a fully reusable piece of code for controlling a certain area of the Angular application. In this article, we’ll look specifically at the selector attribute with examples.
In a nutshell, the selector property enables angular developers to specify how the component should be included in html templates.
It instructs Angular to build and insert an instance of the component wherever the selector tag is found in the parent html file of your angular application.
The selector receives a string value that specifies the CSS selector that will be used by Angular to identify the element in the DOM. We'll utilize it in html templates to include components. If you look at the index.html
file in your angular project, you should find that the body has an <app-root>/app-root>
tag.
We're going to start a new angular project using angular cli. The new project is generated with a component, called AppComponent, which contains an app-root
selector as will be seen next.
What is an angular selector?
We turn a typescript class into an angular component using a decorator with a bunch of metadata attributes. A selector is one of these attributes that we often employ in conjunction with the other component configuration metadata to make a fully working and reusable component.
A selector is often used to identify individual components and to determine how the particular component is rendered in the actual DOM. It’s similar to how we use standard HTML tags to include and select DOM elements except that the angular selector is only available in the context of the application or the module where the component is declared.
Component selectors are CSS selectors that specify how Angular locates a given component inside a Html document. While we often use element selectors (<app-root>/app-root>
), this may be any CSS selector, from a CSS class to an attribute.
When we use the Angular CLI 13 to generate a new component, the newly formed component looks as follows:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
title = 'Hello Angular 13!';
}
Observe that in app.component.ts
, we have one property named selector, as well as the distinctive name used to distinguish the app component in the DOM after it is displayed in the browser. The selector app-root
would result in the component being referenced in the HTML code as <app-root>/app-root>
.
After running our angular 13 app in the browser, we can open the browser developer tools and go to the Elements tab, where we can view the rendered component.
As you can observe, the <app-root>
element is displayed first since it is the root component of our application. If there are any descendant components, they are all placed within the root selector.
Essentially, the component's selector attribute is simply a string that is used to identify the component’s element in the DOM.
The selector name may include an app as a prefix by default when the component is created, but we may change that. Remember that two or more component selectors cannot be the same.
Let's have a look at how we may utilize the selector in Angular 13.
Selectors are also important for preserving uniformity in the names of component selectors and custom specs.
Selectors can be used as an element’s name or attribute.
While it is suggested to utilize element selectors when introducing new components (like we did with app-root
), theoretically any other selector may be used.
You may make the selector as basic or as complicated as you would like, but as a rule of thumb, avoid complicated element selectors except if you possess a very reasonable justification not to.
The basic component requires essentially a selector (to instruct Angular 13 on how to locate the component's instances) and a template (which Angular 13 should render when it finds the element). The component decorator's remaining properties are mandatory. We specified in the earlier example that the AppComponent
will be loaded when Angular 13 encounters the app-root
selector and that the app.component.html
file would be shown when Angular 13 identifies the element.
For instance, below are many approaches for specifying the selector property and using it in HTML.
- name: Use element name as selector.
- .class: Use a class name as a selector.
- [attribute]: Use the name of the attribute as a selector.
We've seen an example of using a selector as an element name, but we're not restricted to that. A selector may also be used as an attribute of an element, just like any other HTML element.
Just like the properties associated with HTML elements such as name, id, class, href, src, value, and others; a selector may also be used as an attribute in Angular 13.
This is rather simple to manage if we need to experiment with component input coming directly from the HTML control/element.
We may use brackets []
in conjunction with a selector, as seen below:
import { Component } from '@angular/core';
@Component({
selector: '[app-root]',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 13';
}
We've simply added an extra brackets to the selector value [app-root]
, thus we must now utilize the selector as an attribute rather than an element.
Open the index.html
file and change the <app-root>
markup to look like this:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My Angular 13 app</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<div app-root> </div>
</body>
</html>
As you tell from the screenshot, the <div>
tag, together with the selector, now works as an element. This indicates that the component selector we specified behaves as an attribute rather than an element.
That's how we distinguish a selector as an attribute from a selector as an element by simply adding []
brackets to the selector string.
Angular 13 selector as a class
Already in this tutorial, we've used a selector as an element and an attribute, however we may additionally utilize it as a class.
We simply need to specify the selector value as the class, and the element will be changed to the class in the HTML DOM, exactly as we did in the previous cases.
Update the app.component.ts
file as follows:
import { Component } from '@angular/core';
@Component({
selector: '.app-root',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 13';
}
We simply added a single dot operator, .
before the selector name, so we can use selector as a class name as follows:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My Angular 13 app</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<div class = "app-root"> </div>
</body>
</html>
To define the class name in this html file, we should use the class property, however as you can see, we have utilized the selector name as a class value.
We can now view the results in the Elements tab of the browser developer tool.
Along with the <div>
element, the class name, app-root
, which is the selector name that we specified in the component file, is added.
We can still display the child elements into the component if we set the selector as a class, like we did in the previous example.
Conclusion
In this article, we learnt about the Angular 13 selectors and how to apply them in various contexts. The selector is one of the important attributes that represents a single component.
- Author: Ahmed Bouchefra Follow @ahmedbouchefra
-
Date:
Related posts
Angular Select Change Event Angular iframe Angular FormArray setValue() and patchValue() Angular Find Substring in String Send File to API in Angular 17 EventEmitter Parent to Child Communication Create an Angular Material button with an icon and text Input change event in Angular 17 Find an element by ID in Angular 17 Find an element by ID from another component in Angular 17 Find duplicate objects in an array in JavaScript and Angular What is new with Angular 17 Style binding to text-decoration in Angular Remove an item from an array in Angular Remove a component in Angular Delete a component in Angular Use TypeScript enums in Angular templates Set the value of an individual reactive form fields Signal-based components in Angular 17 Angular libraries for Markdown: A comprehensive guide Angular libraries for cookies: A comprehensive guide Build an Angular 14 CRUD Example & Tutorial Angular 9 Components: Input and Output Angular 13 selectors Picture-in-Picture with JavaScript and Angular 10 Jasmine Unit Testing for Angular 12 Angular 9 Tutorial By Example: REST CRUD APIs & HTTP GET Requests with HttpClient Angular 10/9 Elements Tutorial by Example: Building Web Components Angular 10/9 Router Tutorial: Learn Routing & Navigation by Example Angular 10/9 Router CanActivate Guards and UrlTree Parsed Routes Angular 10/9 JWT Authentication Tutorial with Example Style Angular 10/9 Components with CSS and ngStyle/ngClass Directives Upload Images In TypeScript/Node & Angular 9/Ionic 5: Working with Imports, Decorators, Async/Await and FormData Angular 9/Ionic 5 Chat App: Unsubscribe from RxJS Subjects, OnDestroy/OnInit and ChangeDetectorRef Adding UI Guards, Auto-Scrolling, Auth State, Typing Indicators and File Attachments with FileReader to your Angular 9/Ionic 5 Chat App Private Chat Rooms in Angular 9/Ionic 5: Working with TypeScript Strings, Arrays, Promises, and RxJS Behavior/Replay Subjects Building a Chat App with TypeScript/Node.js, Ionic 5/Angular 9 & PubNub/Chatkit Chat Read Cursors with Angular 9/Ionic 5 Chat App: Working with TypeScript Variables/Methods & Textarea Keydown/Focusin Events Add JWT REST API Authentication to Your Node.js/TypeScript Backend with TypeORM and SQLite3 Database Building Chat App Frontend UI with JWT Auth Using Ionic 5/Angular 9 Install Angular 10 CLI with NPM and Create a New Example App with Routing Styling An Angular 10 Example App with Bootstrap 4 Navbar, Jumbotron, Tables, Forms and Cards Integrate Bootstrap 4/jQuery with Angular 10 and Styling the UI With Navbar and Table CSS Classes Angular 10/9 Tutorial and Example: Build your First Angular App Angular 9/8 ngIf Tutorial & Example Angular 10 New Features Create New Angular 9 Workspace and Application: Using Build and Serve Angular 10 Release Date: Angular 10 Will Focus on Ivy Artifacts and Libraries Support HTML5 Download Attribute with TypeScript and Angular 9 Angular 9.1+ Local Direction Query API: getLocaleDirection Example Angular 9.1 displayBlock CLI Component Generator Option by Example Angular 15 Basics Tutorial by Example Angular 9/8 ngFor Directive: Render Arrays with ngFor by Example Responsive Image Breakpoints Example with CDK's BreakpointObserver in Angular 9/8 Angular 9/8 DOM Queries: ViewChild and ViewChildren Example The Angular 9/8 Router: Route Parameters with Snapshot and ParamMap by Example Angular 9/8 Nested Routing and Child Routes by Example Angular 9 Examples: 2 Ways To Display A Component (Selector & Router) Angular 9/8 Tutorial: Http POST to Node/Express.js Example Angular 9/8 Feature and Root Modules by Example Angular 9/8 with PHP: Consuming a RESTful CRUD API with HttpClient and Forms Angular 9/8 with PHP and MySQL Database: REST CRUD Example & Tutorial Unit Testing Angular 9/8 Apps Tutorial with Jasmine & Karma by Example Angular 9 Web Components: Custom Elements & Shadow DOM Angular 9 Renderer2 with Directives Tutorial by Example Build Progressive Web Apps (PWA) with Angular 9/8 Tutorial and Example Angular 9 Internationalization/Localization with ngx-translate Tutorial and Example Create Angular 9 Calendar with ngx-bootstrap datepicker Example and Tutorial Multiple File Upload with Angular 9 FormData and PHP by Example Angular 9/8 Reactive Forms with Validation Tutorial by Example Angular 9/8 Template Forms Tutorial: Example Authentication Form (ngModel/ngForm/ngSubmit) Angular 9/8 JAMStack By Example Angular HttpClient v9/8 — Building a Service for Sending API Calls and Fetching Data Styling An Angular 9/8/7 Example App with Bootstrap 4 Navbar, Jumbotron, Tables, Forms and CardsHands-on Angular eBook
Subscribe to our Angular newsletter and get our hands-on Angular book for free!
