Welcome to the Component Selector lesson in Angular! This tutorial will guide you through understanding and using one of Angular's powerful features. By the end of this lesson, you'll be able to select and interact with Angular components like a pro šÆ
In Angular, a component selector is a string that is used to identify the component and attach it to the DOM (Document Object Model). It consists of two parts: the local name and the optional prefix.
š Local Name: It's the unique name given to an Angular component, and it's case-insensitive.
š Selector Prefix (optional): It's a string added before the local name to create a unique CSS scope. This can be useful when you have multiple components sharing the same local name.
Let's start by creating a simple component. Open your terminal, navigate to your Angular project, and run the following command:
ng generate component my-componentThis command will create a new component named my-component for us.
Now, let's take a look at the generated files:
src/app/my-component/my-component.component.ts (TypeScript file)src/app/my-component/my-component.component.html (HTML template)src/app/app.module.ts (Module where our new component will be added)Now, let's set our component selector. Open the my-component.component.ts file and look for the selector property:
import { Component } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent {
// ...
}Here, app-my-component is the component selector. You can change it to a name that suits your component.
Now that we've created and configured our component, let's use it in our application. Open the app.component.html file and add the following code:
<app-my-component></app-my-component>Now, run your Angular application:
ng serveYou should see your my-component being displayed on the screen š”
What is the purpose of the `selector` property in an Angular component?
In the next lessons, we'll dive deeper into Angular components, learning how to pass data, use services, and handle events between components. Stay tuned! š
Happy coding! š