5

I have a nested component SearchBar as a child of my Header. My component definition:

@Component({
  moduleId: module.id,
  selector: 'search-form',
  templateUrl: 'search-form.component.html',
  styleUrls: [ 'search-form.component.css']
})

search-form.component.html is using the following directive inside:

<tag-input placeholder="Add tags ..." 
    [(model)]="tagsArray" 
    (tagsChanged)="onTagsChange($event)"
    (tagsAdded)="onTagsAdded($event)"
    (tagRemoved)="onTagRemoved($event)"
    [delimiterCode]="[32]"></tag-input>

and inside search-form.component.html I have the following rule:

.ng2-tag-input-field {
    padding: 5px;
    border-radius: 6px;
    margin-right: 10px;
    direction: ltr;
    text-align: right;
}

The CSS rules have no effect on the nested directive, unless I put the CSS inside Styles.css file. Why this isn't working as expected?

Yuvals
  • 3,094
  • 5
  • 32
  • 60

1 Answers1

12

You need to change your component's viewEncapsulation.

import { ViewEncapsulation} from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'search-form',
  templateUrl: 'search-form.component.html',
  styleUrls: [ 'search-form.component.css'],
  encapsulation: ViewEncapsulation.None
})

Angular 2 comes with view encapsulation built in, which enables us to use Shadow DOM. There are three view encapsulation types:

1) ViewEncapsulation.None - No Shadow DOM at all. Therefore, also no style encapsulation.

2) ViewEncapsulation.Emulated - No Shadow DOM but style encapsulation emulation.

3) ViewEncapsulation.Native - Native Shadow DOM with all it’s goodness.

For more see VIEW ENCAPSULATION IN ANGULAR 2

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • 2
    If I use ViewEncapsulation.None it breaks my imported (nested) class. I want to effect down the waterfall (the nested component) but not be effected from outside the host component. – Yuvals Oct 25 '16 at 20:35
  • @Yuvals I don't understand your case clearly, but I think the problem is in the view encapsulation. Try to read the article given above – Suren Srapyan Oct 25 '16 at 20:40
  • 1
    I updated the explanation - the problem is that I can't effect from outside a directive with CSS rules, unless the rules are in global styles.css – Yuvals Oct 26 '16 at 11:04
  • This helped me, i had some parent css that i could not get to work on my child component. .full-screen .info-box { height: 50vh; } Where my info-box was my child element. With "ViewEncapsulation.None", my info-box had its height set to 50vh. – balslev Jun 21 '17 at 08:22
  • @balslev Very glad for you – Suren Srapyan Jun 21 '17 at 08:23