3

I need to add components dynamically from triggered events, i´ve managed to get it working with loadasroot and loadnexttolocation, but the problem is that those only return a promise for the ComponentRef and i cant find a wat to access properties and calling methods in the added components. Ive read some threads about the loadintolocation but it seems that they removed that after releasing the candidate?

1
  • 1
    Maybe you could publish some code to show how far you have got, and what you need to do next? Commented Jun 13, 2016 at 8:03

2 Answers 2

1

Now you can use the ComponentResolver class this way. On the ComponentRef instance, you can access both properties and methods of the newly created component.

@ViewChild('target', {read: ViewContainerRef}) target;

constructor(private resolver: ComponentResolver) {}

createComponent() {
  this.resolver.resolveComponent(MyComp).then(
    (factory:ComponentFactory<any>) => {
      var cmpRef = this.target.createComponent(factory);
      var cmp = cmpRef.instance;
    });
}
Sign up to request clarification or add additional context in comments.

Comments

1
then(cmpRef:ComponentRef => {
  cmpRef.instance.myProp = someValue;
  cmpRef.instance.someOutput.subscribe(val => this.someOtherOutput.next(val));
});

See also Angular 2 dynamic tabs with user-click chosen components for the new way ViewContainerRef.createComponent().

DynamicComponentLoader is deprecated.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.