角度2组件可以与属性选择器一起使用吗?

Teh*_*One 25 angular

我们目前有一个现有的小型Angular 1项目,该项目在内部部署Sharepoint 2013环境中使用.对于我们内容的大部分内容,我们在Sharepoint环境中使用发布页面.

使用Angular 1,我们可以定义要限制的指令:匹配属性名称,标记名称,注释或类名称.我们创建的大多数指令都是属性或标记名称.首选项将是标记名称,但Sharepoint上的发布平台会删除未知元素.这意味着我们留下了使用属性,以便将我们的指令带入发布页面.但是使用Angular 2,我只看到了由标签名称实现的组件.

Angular 2是否可以使用属性名称来使用我们的组件?由于Sharepoint发布平台的限制,这是我们的要求.

谢谢.

acd*_*ior 47

是的,装饰器的selector属性@ComponentCSS选择器(或其子集):

selector: '.cool-button:not(a)'

指定在模板中标识此指令的CSS选择器.支持的选择包括element,[attribute],.class,和:not().
难道支持父子关系选择.

来源: Angular Cheat Sheet/Directive Configuration,@Component继承.

这样你就可以使用[name-of-the-attribute](即CSS属性选择器),例如:

@Component({
    selector: "[other-attr]",
    ...
})
export class OtherAttrComponent {
Run Code Online (Sandbox Code Playgroud)

Se demo plunker在这里.

通常的方法是CSS类型(AKA元素或标记)选择器:

@Component({
    selector: "some-tag",
    ...
})
Run Code Online (Sandbox Code Playgroud)

它将标签与名称相匹配some-tag.

您甚至可以拥有一个与标签或属性匹配的组件:

@Component({
    selector: "other-both,[other-both]",
    template: `this is other-both ({{ value }})`
})
export class OtherBothComponent {
Run Code Online (Sandbox Code Playgroud)

Demo plunker包含所有三个示例.

是否[attributeName="attributeValue"]支持?

是.但请注意引用.在当前实现中,选择器[attributeName="attributeValue"]实际匹配<sometag attributeName='"attributeValue"'>,因此在提交此方法之前进行测试.

  • 是`[attributeName ="attributeValue"]`支持吗? (2认同)
  • Angular CLI附带的linter将组件称为属性.有没有办法在每个文件的基础上禁用该规则? (2认同)
  • @Votemike我还没有找到一种方法来禁用错误但是如果你添加一个元素选择器,除了属性选择器之外,错误就会消失.例如,`selector:"my-selector,[my-selector]"` (2认同)

Har*_*inh 10

是的,根据这个https://angular.io/docs/ts/latest/guide/cheatsheet.html(组件和指令一般非常相似).而不是使用元素选择器:

selector: 'custom-element-name'
Run Code Online (Sandbox Code Playgroud)

使用:

selector: '[custom-attribute-name]'
Run Code Online (Sandbox Code Playgroud)

在您的父组件的模板中:

<div custom-attribute-name></div>
Run Code Online (Sandbox Code Playgroud)


小智 9

@Component装饰器支持,元素选择器,属性选择器和类选择器的选择器属性:

1.元素选择器:

@Component({
 selector: 'app-servers'
})
Run Code Online (Sandbox Code Playgroud)

用法: <app-servers></app-servers>

2.属性选择器:

@Component({
 selector: '[app-servers]'
})
Run Code Online (Sandbox Code Playgroud)

用法: <div app-servers></div>

3.班级选择器:

@Component({
 selector: '.app-servers'
})
Run Code Online (Sandbox Code Playgroud)

用法: <div class="app-servers"></div>

注意: Angular 2不支持id和伪选择器


Ale*_*nov 6

绝对.基本上这只是一个CSS选择器,所以如果你需要使用属性,你只需这样做:

@Component({
    selector: "my-tag[with-my-attribute]"
})
Run Code Online (Sandbox Code Playgroud)