giozh
giozh

Reputation: 10068

Angular2: insert component into a certain position

i've this template file for my component:

<form (ngSubmit)="onSubmit()" #scheduleForm="ngForm" *ngIf="schedule">
    <div #placeholder></div>

</form>

and i would to add two component into placeholder div. This is my code for adding components inside ngOnInit:

const factory = this.componentFactoryResolver.resolveComponentFactory(ExternalComponent);
    let ref = this.viewContainerRef.createComponent(factory);
    ref.changeDetectorRef.detectChanges();
     ref = this.viewContainerRef.createComponent(factory);
    ref.changeDetectorRef.detectChanges();

Where ExternalComponent is the component i would put inside. With this code, ExternalComponents are added at the end of template (after login form). How can i put it inside #placeholder div?

Upvotes: 1

Views: 926

Answers (1)

yurzui
yurzui

Reputation: 214017

That is by design. https://github.com/angular/angular/issues/9035

If you want your dynamic component to be placed inside div add a template or ng-container(they are not stamped to the DOM) inside div and use it.

@Component({
  selector: 'my-app',
  template: `
      <div>
        <ng-container #placeholder></ng-container>
      </div>`
})
export class AppComponent implements OnDestroy { 
  @ViewChild('placeholder', { read: ViewContainerRef }) placeholderContainer: ViewContainerRef;

  compRef: ComponentRef<any>;

  constructor(private resolver: ComponentFactoryResolver) {}

  ngOnInit() {
    const factory = this.resolver.resolveComponentFactory(MyComponent);
    let compRef = this.placeholderContainer.createComponent(factory);
    this.compRef = compRef;
  }

  ngOnDestroy() {
    this.compRef.destroy();
  }
}

Plunker Example

Upvotes: 0

Related Questions