Angular 2-更改零部件选择器 [英] Angular 2—change component selector

查看:147
本文介绍了Angular 2-更改零部件选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

角度2文档表示要定义组件像这样,使用魔术字符串作为选择器名称:

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';
}

如果这样做,我是否会坚持使用<card>作为将来使用此组件的唯一方法?使用此选择器的应用程序只能具有一种类型的组件吗?例如,是否可以使用第三方库中的<card>,还可以使用我自己的<card>?

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>?

这在React中是微不足道的,因为组件名称只是变量.

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>

我问的原因之一是这样,我可以知道是否像Angular 1和Objective-C一样对Angular 2组件选择器命名空间:

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'

推荐答案

您应该为Angular2组件选择器命名空间(但不能使用ng- ;-)

You should namespace Angular2 component selectors (but not with ng- ;-) )

我认为您不能导入2个包含具有相同选择器的元素的模块(未尝试).

I think you can't import 2 modules that contain elements with the same selector (not tried).

这将限制您在一个模块中使用特定的选择器一个组件. 如果遇到冲突,您可能可以将代码拆分为2个模块,其中一个模块从ModuleA导入<card>,另一个模块从ModuleB导入<card>.

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.

组件是模块范围的,这使您能够将组件与具有相同选择器的第三方组件一起使用,例如问题示例中的Composable React组件.

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.

要使用与第三方<card>编写的<card>,可以将第三方组件与另一个属于导入模块的组件包装在一起,然后使用包装器组件.

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.

更新

有关更改根组件选择器的信息,请参见

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

这篇关于Angular 2-更改零部件选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆