Currently I am trying to understand Angular a bit better, especially under the hood. And I noticed that if I have Angular Router set up, and I am adding multiple selectors that these actualy get added. Because under the hood its all just 'ng-container' made by Angular Router.
I was wondering if someone has a bit more in-depth information about how this works? Because I don't realy understand how this is possible. According to angular the selector should be used to select HTML.
Kind regards
Edit: My question seemed to be unclear accoridng to MGX, so here is some more context then.
If you look at this sandbox: https://codesandbox.io/s/angular-45-router-demo-forked-9d14bx?file=/src/app/product-list/product-list.component.ts
There is a product-list component. If I change the selector, the page breaks. Because angular wants me to put in a valid selector in the component decorator.
But if you look at this sandbox: https://codesandbox.io/s/angular-45-router-demo-forked-h87emi?file=/src/app/product-list/product-list.component.ts
There is a router involved, and when I put in a random class 'monkey' into the selector. It suddenly gets added, instead of a breaking page.
So the question is: How does the angular router does this? And why does this work? Why wont this break.
CodePudding user response:
Add the <router-outlet></router-outlet>
in your app.component.html
<div style="text-align: center;">
<h1>
Welcome to {{ title }}!
</h1>
</div>
<div>
<product-list></product-list>
<router-outlet></router-outlet>
</div>
updated demo link https://codesandbox.io/s/angular-45-router-demo-stackoverflow-5xd7zj?file=/src/app/app.component.html:68-232
CodePudding user response:
The component's class is used (new ProductListComponent()
) when the component is instantiated via the Angular Router - that's why no matter what your selector is Angular will still render the component.
The component's selector is used when you reference a component in a HTML template - Angular has to find the component by selector in the components registry.
With the example given, if you want to render a component with selector product-list .monkey
the following has to be present in the HTML template:
// element matches a component from the registry by the `product-list .monkey` selector
<product-list ></product-list>
// element can't be found because there's no component with such selector
<product-list></product-list>