我想为组件选择器使用元素ID,但是它不起作用。

Angular不允许这样做吗?如果是这样,为什么不呢?

(因此.btnAction的选择器匹配,并且按钮被插入到组件1的模板中,但是#btnAction不插入)

我不确定这是否有必要,但是这是我确认其他CSS选择器(如类和属性)有效的代码,但ID无效。

组件1

@Component({
    selector: 'myelement',
    template: `<div id="btnAction" class="btnAction"></div>`,
    directives: [ActionBtn]
})

组件2
@Component({
    selector: '#btnAction',
    template: `<button>{{btnTitle}}</button>`
})

最佳答案

是!!!

角度2+也支持ID选择器。
我们可以使用元素,类或ID。下面是将起作用的代码。

使用ID选择器的


  • @Component({ selector: '[id=idname]', templateUrl: 'template path', styleUrls: ['css path']})
    使用类选择器

  • @Component({ selector: '.classname', //or '[class=classname]' templateUrl: 'template path', styleUrls: ['css path']})
  • 使用元素选择器
  • @Component({ selector: 'elementname' templateUrl: 'template path', styleUrls: ['css path']})

    10-05 20:32
    查看更多