Jackie Jackie - 2 months ago 16
jQuery Question

How do I append DOM to an Angular 2 component and still get encapsulated styles

I am upgrading an existing Angular 2 app that makes extensive use of JQuery Plugins, D3, and even some React Components (All of which use sizzle so I am pretty sure it applies to all). Since it really doesn't make sense to rewrite all of these at once I am trying to wrap some of them in an Angular 2 Component. To show you what I mean I have a simple component that uses Jquery to add an item to the DOM...

import { Component, AfterViewInit, ElementRef } from '@angular/core';
declare var $:JQueryStatic;
selector: 'px-spinner',
template: String(require('./spinner.template')),
styles: [require('!raw!stylus-loader!./spinner.styles')]
export class SpinnerComponent implements AfterViewInit{
constructor(public el:ElementRef){}
$(this.el.nativeElement).append("<div class='output'>Output 2</div>")

The problem here is the styles are not applied to output 2. When I look at the DOM the reason becomes apparent...

<ng-spinner class="ng-scope" id="NG2_UPGRADE_0_pxSpinner_c0" _nghost-ylc-1="">
<div _ngcontent-ylc-1="" class="start">
<div _ngcontent-ylc-1="" class="output">output 1</div>
<div class="output">Output 2</div>

The DOM Element added by JQuery is missing the
. Is there a way to have Ng2 add this when JQuery injects the DOM?


The question is similar to this one (Angular2 - adding [_ngcontent-mav-x] to styles) but I guess the question is how do I include the injected dom in the ViewEncapsulation?


If you use a style like

:host .output {

it should be applied.

If this doesn't work use

:host /deep/ .output {