从 HTML 中删除/替换组件的选择器标签 [英] Remove/replace a component's selector tag from HTML
问题描述
我正在开始使用 Angular 2(版本 2.0.0-alpha.46)并创建一些组件.
使用以下代码创建组件时:
打字稿:
import {ComponentMetadata as Component, ViewMetadata as View} from 'angular2/angular2';@成分({选择器:'我的组件'})@看法({模板:'<div class="myClass">你好我的组件</div>'})导出类 MyCompoent{构造函数(){console.info('我的组件安装成功');}}
HTML:
它工作正常,但是当我执行 Inspect element
时,我可以看到这样生成的标记:
输出 HTML
<div>你好,我的组件</div><我的组件>
问题
它在 HTML 中保留了 <my-component>
标签,并且我的一些 CSS 没有按预期工作.
问题
有没有办法删除类似于 angular 1 的
标签(replace: true
在指令中)?
根据 https://github.com/angular/angular/issues/3866 因为这似乎不是一个好主意.
作为一种解决方法,您可以在组件中使用属性选择器,例如
<打击>
选择器:'[我的组件]'
选择器:'[myComponent]'
然后像
一样使用它<打击>
你好我的组件
你好我的组件
提示
指令选择器应该是驼峰式而不是蛇式.Snake-case 仅用于元素选择器,因为自定义元素需要 -
.Angular 不依赖于组件是自定义元素,但无论如何遵守此规则被认为是一种很好的做法.Angular 适用于camelCase 属性,并将它们与所有指令(*ngFor
、ngModel
、...)一起使用,Angular 样式指南也建议使用它们.
I am getting started with the Angular 2 (version 2.0.0-alpha.46) and creating a few components.
When creating the component with the below code:
Typescript:
import {ComponentMetadata as Component, ViewMetadata as View} from 'angular2/angular2';
@Component({
selector: 'my-component'
})
@View({
template: '<div class="myClass">Hello My component</div>'
})
export class MyCompoent{
constructor() {
console.info('My Component Mounted Successfully');
}
}
HTML:
<my-component></my-component>
It works fine, but when i do Inspect element
, I can see a tag generated like this:
Output HTML
<my-component>
<div>Hello My component</div>
<my-component>
Problem
it keeps the <my-component>
tag in the HTML, and some of my CSS are not working as expected.
Question
Is there a way to remove the <my-component>
tag similar to angular 1 (replace: true
in the directive)?
Replace was deprecated in AngularJS 1.x according to https://github.com/angular/angular/issues/3866 because it seemed to not be a good idea.
As a workaround you can use an attribute selector in your component like
selector: '[my-component]'
selector: '[myComponent]'
and then use it like
<div my-component>Hello My component</div>
<div myComponent>Hello My component</div>
hint
Directive selectors should be camelCase instead of snake-case.
Snake-case is only used for element selectors, because the -
is required for custom elements. Angular doesn't depend on components being custom elements, but it's considered good practice to comply with this rule anyway.
Angular works fine with camelCase attributes and uses them with all directives (*ngFor
, ngModel
, ...), and is also suggested by the Angular style guide.
这篇关于从 HTML 中删除/替换组件的选择器标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!