Jimmy Wijaya
Jimmy Wijaya

Reputation: 161

Get ViewContainerRef from Component

i want to create nested component in angular 4

this is chooser component

import {InputComponent} from './input/input.component'
import {BlockComponent} from './block/block.component'

export const FormChooser = {
  Block: BlockComponent,
  Input: InputComponent
}

this is component builder

const component = FormChooser[data.component]
const factory = this.Resolver.resolveComponentFactory(component)

const new_component = this.ViewContainerRef.createComponent(factory)

How to get new_component ViewContainerRef ? so i can use code like this

const another_new_component = new_component.createComponent(factory) // as ViewContainerRef

Thank you...

Upvotes: 12

Views: 23459

Answers (2)

feyzullahyildiz
feyzullahyildiz

Reputation: 677

For Angular +8

import { InputNumberComponent } from '../input-number/input-number.component';
@Component({
  selector: 'app-dynamic-form',
  templateUrl: './dynamic-form.component.html',
  styleUrls: ['./dynamic-form.component.scss']
})
export class DynamicFormComponent implements OnInit {

  @ViewChild('ref', { read: ViewContainerRef }) vcRef: ViewContainerRef;
  constructor(private resolver: ComponentFactoryResolver) { }

  ngOnInit() {
    const comp = this.resolver.resolveComponentFactory(InputNumberComponent)
    this.vcRef.createComponent(comp)
  }

}

Upvotes: 7

yurzui
yurzui

Reputation: 214175

You can inject ViewContainer in constructor of dynamic component

class BlockComponent {
  constructor(public vcRef: ViewContainerRef) {}
}

const factory = this.Resolver.resolveComponentFactory(BlockComponent)

const newComponentRef = this.ViewContainerRef.createComponent(factory);
const newComponentVcRef = newComponentRef.instance.vcRef; 

or use @ViewChild to get reference to ViewContainerRef

 template: '<ng-container #ref></ng-container>'
})
class BlockComponent {
  @ViewChild('ref') vcRef: ViewContainerRef;
}

const factory = this.Resolver.resolveComponentFactory(BlockComponent )

const newComponentRef = this.ViewContainerRef.createComponent(factory);
const newComponentVcRef = newComponentRef.instance.vcRef; 

Upvotes: 10

Related Questions