Vb Dev
Vb Dev

Reputation: 247

Angular 2 apply existing CSS class to a dynamic injected component

I inject dynamically components to the DOM with:

let factory  = this.componentFactoryResolver.resolveComponentFactory(component); 
let injector = ReflectiveInjector.fromResolvedProviders([], refDOM.parentInjector);
let comp     = factory.create(injector);
comp.changeDetectorRef.detectChanges();
refDOM.insert(comp.hostView,position);
return comp

I have a css class:

.vbox {

       display: -webkit-box;
       display:    -moz-box;
       display:         box;

       -webkit-box-orient: vertical;
          -moz-box-orient: vertical;
           -ms-box-orient: vertical;
               box-orient: vertical;


       display: -webkit-flex;
       display:    -moz-flex;
       display:     -ms-flex;
       display:         flex;

       -webkit-flex-direction: column;
          -moz-flex-direction: column;
           -ms-flex-direction: column;
               flex-direction: column;
}

I want to apply class vbox to the :host css tag of the dynamic injected component. Since the dynamic component isn't defined in the html file before being injected, I cannot apply existing class styles like: class="vbox".

Is it possible to achieve this?

Thank you.

Upvotes: 1

Views: 875

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658263

You can either inside the dynamic component add

@HostBinding('class.vbox')
isVboxClass:boolean = false; // or true by default

and then enable it using

comp.instance.isVboxClass = true;

or just

comp.location.classList.add('vbox');

Upvotes: 1

Related Questions