Angular 2——改变组件选择器 [英] Angular 2—change component selector

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

问题描述

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

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

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:

选择器:'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 导入 ,另一个模块从 导入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.

要使用你用第三方编写的,你可以用另一个组件包装第三方组件导入的模块,然后改用包装器组件.

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

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

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