Angular 2—change component selector

孤人 提交于 2020-01-03 14:36:49

问题


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'


回答1:


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.

EDIT (updating answer from comments)

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

  • https://github.com/angular/angular/pull/14750
  • https://github.com/angular/angular/issues/7136
  • https://github.com/angular/angular/issues/13035


来源:https://stackoverflow.com/questions/39533051/angular-2-change-component-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!