How to handle/provide @Input and @Output properties for dynamically created Components in Angular 2?

The idea is to dynamically create (in this case) the SubComponent when the createSub method is called. Forks fine, but how do I provide data for the @Input properties in the SubComponent. Also, how to handle/subscribe to the @Output events the SubComponent provides?

Example: (Both components are in the same NgModule)

AppComponent

@Component({
  selector: 'app-root'
})  
export class AppComponent {

  someData: 'asdfasf'

  constructor(private resolver: ComponentFactoryResolver, private location: ViewContainerRef) { }

  createSub() {
    const factory = this.resolver.resolveComponentFactory(SubComponent);
    const ref = this.location.createComponent(factory, this.location.length, this.location.parentInjector, []);
    ref.changeDetectorRef.detectChanges();
    return ref;
  }

  onClick() {
    // do something
  }
}

SubComponent

@Component({
  selector: 'app-sub'
})
export class SubComponent {
  @Input('data') someData: string;
  @Output('onClick') onClick = new EventEmitter();
}
share|improve this question
2  
In the past you could do something like this.. ref.instance.someData = someData. I am not sure if that is still the case though. – Kris Hollenbeck Nov 2 '16 at 14:26
2  
That still works. There is no other way (except using shared services to communicate). stackoverflow.com/questions/36325212/… contains some more details. – Günter Zöchbauer Nov 2 '16 at 14:29
    
@KrisHollenbeck @Günter Zöchbauer Thanks. So everytime the data changes in the parent component, i have to set it like 'ref.instance.someData = someData' and trigger change detection ('ref.changeDetectorRef.detectChanges();') on my own? And how to find out what property in the sub component is the right on? Could be named completely different ... :/ Maybe use Reflection directly Will try it :) – thpnk Nov 2 '16 at 14:38
    
@thpnk, Yeah I believe so, that sounds right. I haven't tried doing this since one of the later RC versions. I would refer to that post by Gunter Zochbauer for more info. stackoverflow.com/questions/36325212/… – Kris Hollenbeck Nov 2 '16 at 16:22

Found no way other than setting/getting the properties directly on the instance.

Still open: How to find out, which properties are input and output properties and which ones are not.

share|improve this answer
    
There is no support for data-binding with dynamically added components. @Input() and @Output() are meaningless in these components. – Günter Zöchbauer Dec 11 '16 at 10:29

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.