Jim Cooper
Jim Cooper

Reputation: 5027

Issues Styling :host in Angular 2

[Edited to better describe the problem]

I'm having difficulty applying various styles to :host in Angular 2. The simple plunker below demonstrates the problem. At first I thought that certain styles such as margin/padding weren't getting applied, but it seems that the issue is that the host element isn't behaving like a normal element. Notice that I've added a border and padding. The border looks really odd and the padding doesn't move the content inside the element at all (although it does appear to affect the way the border looks. This is the style I'm applying:

:host {padding:10px; border:1px solid red;}

The rendered code looks like this:

<sample-component _nghost-cxm-2="">
  <div _ngcontent-cxm-2="">
    <h3 _ngcontent-cxm-2="">Sample Component</h3>
  </div>
</sample-component>

I can see in dev tools that the styles are being applied to the <sample-component> element, but this is what the page looks like rendered:

Weird border behavior

I would expect the border to wrap the content inside the component but it is behaving oddly. Here is a sample plunker: https://plnkr.co/edit/k7LJcmVlhJINmakBJAau?p=preview

What am I missing?

Upvotes: 6

Views: 3411

Answers (2)

Jim Cooper
Jim Cooper

Reputation: 5027

I just realized what the problem is. Host elements are set to display:inline. Changing the element to display:block fixes the problem. Not sure how I missed this before.

Upvotes: 21

micronyks
micronyks

Reputation: 55443

I already showed you that your plunker is working. Other than that you can use host metaproperty to apply style to host element as shown below,

https://plnkr.co/edit/7JquAioc6lUx9bUrPCiZ?p=preview

@Component({
  selector: 'sample-component',
  template: `
    <div>
      <h3>Sample Component</h3>
    </div>
  `,
  host:{
        'style': 'color:red;padding:50px',
       }
})
export class SampleComponent {}

UPDATE after your edit:

I may not give you an exact answer but there is some problem with <sample-component> element/tag which gets created in DOM. Maybe I understand what you're trying to achieve. I have a workaround for the same.

look at here - https://plnkr.co/edit/yLLsZABJWCrvE0CWHgFy?p=preview

Upvotes: 2

Related Questions