2

May i do something in Angular 9?

@Component({
    selector: "app-custom",
    template: "<h1>Hey, it's me!</h1>"
})
export class CustomComponent {

}

@Component({
    selector: "app-parent",
    template: "{{ someComponent }}"
})
export class Parent {

    someComponent: CustomComponent;

    constructor() {
        this.someComponent = new CustomComponent();
    }
}

I want to render component from variable.

This is example code, in my code i get "custom-component" from my contentchildren and want to render it with my changes

1 Answer 1

1

Here's my understanding of what you're trying to do.

You have a component:

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  public name: string = '';
}

You want to render that component using a variable.

@Component({
  selector: "my-app",
  template: "<ng-container #template></ng-container><p>Welcome</p>"
})
export class AppComponent implements OnInit {
  @ViewChild("template", { static: true, read: ViewContainerRef })
  private vcRef: ViewContainerRef;

  private componentType: Type<HelloComponent>;

  constructor(private componentFactoryResolver: ComponentFactoryResolver) {}

  ngOnInit() {
    this.componentType = HelloComponent;

    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(
      this.componentType
    );

    const componentRef = this.vcRef.createComponent(componentFactory);
    (<HelloComponent>componentRef.instance).name = "John";
  }
}

We use the @ViewChild decorator to find our "template" container, which will hold our component, and reference (read) it as a ViewContainerRef object. This object will give us the ability to create and render our component.

The ComponentFactoryResolver will get the factory used to create our component.

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

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.