1

I know that in order to create a component dynamically you can do something like this

let componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);

let viewContainerRef = this.host.viewContainerRef;
viewContainerRef.clear();

let componentRef = viewContainerRef.createComponent(componentFactory);
componentref.instance.data = someData;

ngOnInit is called right after viewContainerRef.createComponent(), which is before the data property is patched through to the component. In my ngOnInit I have logic that needs all properties in advance. How can I pass my props to the component before it is created?

6
  • Probably duplicate of stackoverflow.com/a/39280103/5043867 Commented Feb 4, 2019 at 4:48
  • I don't think this is a duplicate because that post addresses passing properties, but does not address passing them before ngOnInit as would be the case with a statically added component (and is what I'm interested in). Commented Feb 4, 2019 at 4:52
  • Just a suggestion, might help you anyhow :) Commented Feb 4, 2019 at 4:53
  • you want to check the input property before ngOnInit? Commented Feb 4, 2019 at 5:05
  • Yes like I pass a bunch of data to this component, and in ngOnInit I want to map it in some way and use it in various parts of the component. Commented Feb 4, 2019 at 5:08

1 Answer 1

1

ES6 classes brings a new syntax for setters on object properties.

The set syntax binds an object property to a function to be called when there is an attempt to set that property.

Try this

import { Component, Input , OnInit} from '@angular/core';    
@Component({
  selector: 'hello',
  template: `<h1>Hello {{_name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent implements OnInit {
  _name: string;
  @Input() set name(value) {
    //do your logic here
    this._name = value;
    console.log(value);
  }

  ngOnInit() {

  }
}

Example:https://stackblitz.com/edit/angular-dynamic-com-set

Sign up to request clarification or add additional context in comments.

4 Comments

This is very useful and interesting. But my template is going to have tons of nulls to deal with after creation, which is a huge hassle. The nice thing about routing to a component is I have all of the params I need at component creation time. Is there a way to sort of mimic this routing with components with dynamic component creation? For example, I use the data that is passed in to make a service call. Of course your answer covers this, but I wonder if there are alternatives.
Sorry could not think of any other approach!
What about using providers?
ya great idea Try that!

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.