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?

flyinghigh
  • 235
  • 3
  • 11

1 Answers1

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

Chellappan வ
  • 23,645
  • 3
  • 29
  • 60
  • 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. – flyinghigh Feb 04 '19 at 05:28
  • Sorry could not think of any other approach! – Chellappan வ Feb 04 '19 at 06:19
  • What about using providers? – flyinghigh Feb 05 '19 at 03:15
  • ya great idea Try that! – Chellappan வ Feb 05 '19 at 03:51