从HTML删除/替换组件的选择器标签 [英] Remove/replace a component's selector tag from HTML

查看:219
本文介绍了从HTML删除/替换组件的选择器标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用Angular 2(版本2.0.0-alpha.46)并创建了一些组件.

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:

打字稿:

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>

它工作正常,但是当我执行Inspect element时,我可以看到这样生成的标记:

It works fine, but when i do Inspect element, I can see a tag generated like this:

输出HTML

<my-component>
    <div>Hello My component</div>
<my-component>

问题

它在HTML中保留了<my-component>标记,而我的某些CSS无法按预期工作.

it keeps the <my-component> tag in the HTML, and some of my CSS are not working as expected.

问题

是否有一种方法可以删除类似于角度1(指令中的replace: true)的<my-component>标签?

Is there a way to remove the <my-component> tag similar to angular 1 (replace: true in the directive)?

推荐答案

根据 https://github.com/angular/angular/issues/3866 ,因为这似乎不是一个好主意.

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]'

然后像

<div my-component>Hello My component</div>

<div myComponent>Hello My component</div>

提示

指令选择器应为驼峰式而不是蛇形. Snake-case仅用于元素选择器,因为-对于自定义元素是必需的. Angular并不依赖于组件是否为自定义元素,但是无论如何都要遵守该规则被认为是一种很好的做法. Angular可以很好地使用camelCase属性,并将其与所有指令(*ngForngModel,...)一起使用,并且在《 Angular样式指南》中也有建议.

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屋!

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