ndesign11 ndesign11 - 1 month ago 7
AngularJS Question

Add attributes to Angular 2 Component Selector

I would like to add attributes to the custom selector I create in the angular 2 component implementation.

@Component({
selector: 'my-node', // add attributes to this selector
template: `<div> <ng-content></ng-content> </div>`
})


So that when I do
<my-node>
The dom generates the selector with these extra attributes

<my-node flex="25" layout="row">


I don't want to hard code these attributes every time I do
<my-node>
. I want those attributes to be part of the selectors constructed template.

Something like this is what Im looking for but not seeing anything like it in the api

@Component({
selector: 'my-node',
selectorAttributes: `layout="row"` // generates <my-node layout="row">
template: `<div> <ng-content></ng-content> </div>`
})

Answer

Use host of @Component metadata property.

@Component({
   selector: 'my-node',     // add attributes to this selector 
   template: `<div> <ng-content></ng-content> </div>`,
   host: { // this is applied to 'my-node' in this case
      "[class.some-class]": "classProperty", 
      "[attr.some-attr]": "attrProperty", 
   },   
})

Here is an example plunk . See app/app.component.ts

Comments