ProfK ProfK - 1 year ago 81
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:

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

And it was used like this:


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
decorators, all with different
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
have a name or something?

Answer Source

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download