0

I have created some components through the code like:

resolveCom(com: any, viewContain: ViewContainerRef): ComponentRef<any> {
        let comFac = this.componentFactoryResolver.resolveComponentFactory(com)
        let newCom: ComponentRef<any> = viewContain.createComponent(comFac)
        newCom.changeDetectorRef.detectChanges()
        return newCom
   }

And I dynamic create some compoennts and save them into the array:

let newCom: ComponentRef<any> = this.resolveCom(item, viewContain)
saveCom[key].push(newCom)

The view can show the components that were created.Now i want to hide or show these components but i don't want to destroy them and recreate them. I saved them just now,can i dynamic insert the component that i save to the view ?

oceania
  • 78
  • 8

1 Answers1

0

You access the element using location.nativeElement and then use it to set attributes or properties

newCom.location.nativeElement.hidden = true

or

this.renderer.setElementProperty(newCom.location.nativeElement, 'hidden', true);
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • But the `hidden` attributes seems wasn't supported on IE10 - – oceania Nov 30 '16 at 06:55
  • That was meant as an example. You can use `setElementAttribute()` or `setElementClass()` instead, and add `[hidden] { display: none; }` to your global CSS to get better browser support. https://angular.io/docs/ts/latest/api/core/index/Renderer-class.html – Günter Zöchbauer Nov 30 '16 at 07:04
  • enn..what should I do when I want to create a compoennt with some params? Then the new compoennt can opera the params. – oceania Nov 30 '16 at 08:21
  • Not sure what you mean. Perhaps `newCom.instance.someProp = someValue;` http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 also shows how to do that. – Günter Zöchbauer Nov 30 '16 at 08:23
  • the `someValue` is the data of one component,and i get it,then when i create a new component i pass this data to it by `newCom.instance.someProp = someValue;` , but when the new component change the `someProp`,the `somaValue` dosen't changed? why – oceania Dec 01 '16 at 02:50
  • Thats expected behavior. You can add an observable to the compinent and subscribe to it. `newCom.instance.somePropChange.subscribe(...)` – Günter Zöchbauer Dec 01 '16 at 04:06
  • https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service shows examples how to use observables. – Günter Zöchbauer Dec 01 '16 at 05:41
  • I create a new component, and then i want to dynamically add some Directives' selector to the this new component's template and make it works. Like `render.setElementAttribute(newCom.location,"my directive's selector", "")`. So how can i make it works well with my directive? – oceania Dec 08 '16 at 03:54
  • Ditectives are not instantiated for dynamically added attributes, only when added ststically to a components template. – Günter Zöchbauer Dec 08 '16 at 09:09