7

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>`    
})
2
  • 1
    What are you trying to achieve? Why not put them on the root element of the template? Commented Nov 2, 2016 at 20:27
  • 1
    Have you tried @HostBinding? Commented Nov 2, 2016 at 20:30

2 Answers 2

11

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

Sign up to request clarification or add additional context in comments.

10 Comments

Adding host: '[attr]="componentProp"' errors, can you link to docs with this "host:" implementation please?
Pretty sure this is what I need but still get errors. Can't bind to 'attr' since it isn't a known property of 'my-node'.
If 'my-node' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
"[attr]": ''prop" would work if attr is a native property like disabled. In other cases use "[attr.yourAttr]": ''prop"
I added an example plunk to the answer. Hope it helps
|
8

Another option is to use the HostBinding dectorator

@HostBinding('attr.layout')
layout = 'row';

1 Comment

This one worked great for me. I think it is the best solution because you can put it next to the other class variables like inputs, outputs, private / public component info, etc. It also allows you to predictably set values and get Typescript to analyze your code if you want to evaluate a function as your HostBinding value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.