简体   繁体   中英

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.

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM