Sergey
Sergey

Reputation: 1660

Angular - component selector using ID

I want to use an element ID for a component selector but it doesn't work.

Is this not allowed in Angular? If so why not?

(so a selector of .btnAction matches, and the button is inserted into Component 1's template, but #btnAction doesn't)

I'm not sure this is necessary, but here's the code through which I've confirmed that other CSS selectors work (like class and attribute), but ID's don't.

Component 1

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

Component 2

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

Upvotes: 3

Views: 8668

Answers (1)

Nikesh Kumar
Nikesh Kumar

Reputation: 419

yes!!!

ID selector is also supported by angular 2+. we can use either element, class or id. below is the code which will work.

  1. using id selector

@Component({ selector: '[id=idname]', templateUrl: 'template path', styleUrls: ['css path'] })

  1. using class selector

@Component({ selector: '.classname', //or '[class=classname]' templateUrl: 'template path', styleUrls: ['css path'] })

  1. using element selector

@Component({ selector: 'elementname' templateUrl: 'template path', styleUrls: ['css path'] })

Upvotes: 6

Related Questions