ProfK ProfK - 3 months ago 12
TypeScript Question

Why do all components with Component selectors have to be used in an Angular 2 application?

Please be aware I am working with tutorial code here, so not everything is strictly correct, but it works. Most of the time.

I have a component class that is decorated as follows:

@Component({
selector: "click-here",
template: `
<button (click) = "onClickThere($event)">Click here!</button>
{{clickMessage}}
`
})


And it was used like this:

<body>
<click-here>Loading...</click-here>
</body>


Then I added a new component class, but its decorator has:

selector: "type-here"


When I run the application with
npm start
, I get a legion of errors in the browser, starting with:

The selector "click-here" did not match any elements


Why does every selector have to match an element? Working like this is not feasible; there must be a way to be able to have multiple
Component
decorators, all with different
selector
values, and only use some of them. How would I achieve that? What am I doing wrong that the tutorial hasn't included a correct version of? Must each
Component
have a name or something?

Answer

This is only relevant to the element you instantiate with bootstrap(MyComponent).

If you bootstrap a component and it doesn't match a selector, Angular doesn't know where it should place it. Angular uses the selector to find the place where to insert the component into the DOM.

This also means you can currently bootstrap one component only once inside your page. There are plans to support overriding the selector when a component is passed to bootstrap() but currently this isn't supported.

See also https://github.com/angular/angular/issues/7136

For components used inside MyComponent this doesn't matter. You can have as many components as you want and only use what you need.

Comments