Lets say I have a following angular component:
@Component({
selector: 'app-bar',
templateUrl: './bar.component.html',
styleUrls: ['./bar.component.css']
})
export class BarComponent implements OnInit {
If I instantiate this component I get the following html:
<body>
<my-app _nghost-rkr-c45="" ng-version="10.0.1">
<app-bar _ngcontent-rkr-c45="" _nghost-rkr-c43=""> (*)
<p _ngcontent-rkr-c43="">bar works!</p>
</app-bar>
</my-app>
</body>
Angular has created a tag that corresponds to the component’s selector. Now, let’s say I want to create a component such that it does not have a corresponding tag in the HTML. How can I do that? Let’s say I want to attach my component to a div instead of creating a new tag.
I can do this by modifying the selector decorator. The selector decorator can take any valid CSS selector. So, if I use the class selector, Angular will attach the component instance to the elements that have that class. I create the example below:
@Component({
selector: '.container',
templateUrl: './foo.component.html',
styleUrls: ['./foo.component.css']
})
This component will attach itself to the elements that have a class called container, so the following HTML will be generated:
<body>
<my-app _nghost-jpn-c54="" ng-version="10.0.1">
<app-bar _ngcontent-jpn-c54="" _nghost-jpn-c43="">
<p _ngcontent-jpn-c43="">bar works!</p>
</app-bar>
</my-app>
</body>
Notice that no html tag is created.
I hope you learned something new 🙂