【问题标题】:Selectors name when naming directives命名指令时的选择器名称
【发布时间】:2017-04-05 22:33:55
【问题描述】:

我在 Angular2 中看到了指令,以两种似乎工作方式相同的方式命名:

第一个@Directive({ selector: '[myDirective]' })

第二个@Directive({ selector: 'myDirective' })

两者有什么区别?

我还看到了像下面这样的指令,这让我更加困惑

@Directive({
    selector: "[ngModel][typeValidate]",
    host: {
        "(input)": "validate($event)"
    }
})

任何人都可以解释一下吗?

【问题讨论】:

    标签: angular angular2-directives


    【解决方案1】:

    @Directive 装饰器的selector 属性是CSS selector -- see "Directive Configuration" at the cheatsheet。因此:

    • 选择器[myDirective] 匹配所有具有属性 myDirective 的元素。
      • 示例:<some-tag myDirective="doesnt matter"></some-tag>
    • 选择器myDirective 匹配所有以myDirective 作为标签的元素
      • 示例:<myDirective></myDirective>
    • 类似地,[ngModel][typeValidate] 匹配具有ngModelmyDirective 属性的所有元素。
      • 示例:<some-tag myDirective="a" ngModel="b"></some-tag>

    【讨论】:

      【解决方案2】:

      将选择器视为 CSS 选择器,

      指定一个 CSS 选择器,在 模板。支持的选择器包括 element、[attribute]、.class、 并不是()。不支持父子关系选择器。

      所以myDirective 是一个元素选择器

       <myDirective></myDirective>
      

      [myDirective] 是一个属性选择器

       <div myDirective=""></div>
      

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-23
        • 1970-01-01
        • 1970-01-01
        • 2017-06-22
        • 2011-04-15
        • 2011-04-13
        • 2019-04-13
        相关资源
        最近更新 更多