Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>`    
})
like image 472
ndesign11 Avatar asked Nov 02 '16 20:11

ndesign11


2 Answers

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

like image 88
Yaroslav Grishajev Avatar answered Oct 04 '22 21:10

Yaroslav Grishajev


Another option is to use the HostBinding dectorator

@HostBinding('attr.layout')
layout = 'row';
like image 32
Martin Avatar answered Oct 04 '22 22:10

Martin