Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 715
Jim Cooper Avatar asked Oct 08 '16 06:10

Jim Cooper


2 Answers

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.

like image 69
Jim Cooper Avatar answered Sep 30 '22 03:09

Jim Cooper


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

like image 34
Nikhil Shah Avatar answered Sep 30 '22 04:09

Nikhil Shah