Angular 2 - Apply conditional style to a directive's child HTML element
Add a style to the child-component
@Component({
selector: 'child-component',
inputs: ['item'],
template: `
<div class="This is where I really want to apply the style">
{{ item.val }}
</div>
`,
styles: [`
:host(.bordered) > div {
// if this selector doesn't work use instead
// child-component.bordered > div {
border: 3px solid red;
}
`],
})
export class ChildComponent {}
I found a better way to solve this making good use of Angular2 features.
Specifically instead of doing trickery with :host and CSS functionality you can just pass in a variable to the child component by changing:
[class.bordered]='isSelected(item)'
being set in the element of the child class change it to
[isBordered]='isSelected(item)'
Then on the div you'd like to apply the bordered class to in the template of the child component just add:
[ngClass]='{bordered: isBordered}'
Here is the full code with the change:
@Component({
selector: 'parent-component',
directives: [ChildComponent],
template: `
<child-component
*ngFor='#item of items'
[item]='item'
(click)='clicked(item)'
[isBordered]='isSelected(item)'>
</child-component>
`
})
export class ParentComponent {
items: Item[];
currentItem: item;
constructor(private i: ItemService) {
this.items = i.items;
}
clicked(item: Item): void {
this.currentItem = item;
}
isSelected(item: Items): boolean {
if (!item || !this.currentItem) {
return false;
}
return item.val === this.currentItem.val;
}
}
@Component({
selector: 'child-component',
inputs: ['item'],
template: `
<div [ngClass]='{bordered: isBordered}'>
{{ item.val }}
</div>
`
})
export class ChildComponent {}