create dynamic anchorName/Components with ComponentResolver and ngFor in Angular2

前端 未结 2 609
心在旅途
心在旅途 2020-12-06 12:37

I need to create unique Anchor Names/Components in a ngFor loop to use it with ComponentResolver.resolveComponent.

2条回答

Location directive:

@Directive({
  selector: '[location]'
})
class Location {
  @Input() h: number;
  @Input() v: number;

  constructor(public viewContainerRef: ViewContainerRef) {
  }
}

Component

@Component({
  selector: 'example-cmp',
  directives: [CORE_DIRECTIVES, Location]
})
export class ExampleComponent implements AfterViewInit {
  public arr: Array> = [];
  public componentRef: ComponentRef;

  @ViewChildren(Location) private locations: QueryList;

  constructor(private resolver: ComponentResolver) {
  }

  ngAfterViewInit() {
    this.loadTag(0,0,SomeViewComponent);
  }

  loadTag(x:number, y:number, component) {
    let viewContainerRef: ViewContainerRef = null;
    let locs = this.locations.toArray();
    for (let i = 0; i < locs.length; i++) {
      if (+locs[i].h === x && +locs[i].v === y) {
        viewContainerRef = locs[i].viewContainerRef;
      }
    }
    if (viewContainerRef != null) {
      var injector = ReflectiveInjector.fromResolvedProviders(ReflectiveInjector.resolve([
        provide(NeededAttribute, { useValue: 42 })]),
        this.componentRef.injector);

      this.resolver.resolveComponent(component).then((factory: ComponentFactory) => {
        var compRef: ComponentRef = viewContainerRef.createComponent(factory, -1, injector);
      });
    }
  }
}

提交回复
热议问题