The Angular 2 docs say to define a component like this, using a magic string for the selector name:
import { Component } from '@angular/core';
@Component({
selector: 'card',
template: `
<div class="card">{{title}}</card>
`
})
export class Card {
title = 'Card Title';
}
If I do this, am I stuck with <card>
as the only way to use this component in the future? Can an app have only one type of component with this selector? For example, is it possible to use a <card>
from a third-party library, and also use my own <card>
?
This is trivial in React, because component names are just variables.
import OtherCard from 'card'
const Card = title => <div className="card">{title}</div>
const Composable = title => <OtherCard><Card title={title} /></OtherCard>
One of the reasons I ask is so I can know whether to namespace Angular 2 component selectors like in Angular 1 and Objective-C:
selector: 'initech-card'
Two or more components use the same element selector. Because there can only be a single component associated with an element, selectors must be unique strings to prevent ambiguity for Angular.
To use selector as directive, change is required in the selector of the child component. Selector name need to be closed in square bracket, just like in case of property binding. Now the child component can be included in the parent using directive like this.
What is a Selector in Angular? A selector is one of the properties of the object that we use along with the component configuration. A selector is used to identify each component uniquely into the component tree, and it also defines how the current component is represented in the HTML DOM.
You should namespace Angular2 component selectors (but not with ng-
;-) )
I think you can't import 2 modules that contain elements with the same selector (not tried).
This limits you to one component with a specific selector within one module.
If you encounter a collision you might be able to split your code in 2 modules where one module imports <card>
from ModuleA
and the other module imports <card>
from ModuleB
.
I wouldn't expect such collisions to happen a lot.
Components are module-scoped, which gives you the ability to use components with third-party components with the same selector, like in the Composable
React component in the example in the question.
To use a <card>
you wrote with a third-party <card>
, you can wrap the third-party component with another component that is part of an imported module and then use the wrapper component instead.
update
For changing the selector of the root component see also
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With