首页 > 解决方案 > 动态创建自动完成组件并在 Angular 中为每个组件设置数据源

问题描述

我正在从服务器动态加载几个控件,例如下拉菜单、文本框等。在客户端,我想遍历这些项目,每当我有下拉菜单时,创建一个自动完成,设置它的数据源,并且我希望在提交表单后能够访问它。我到达使用@ViewChildren,但我没有找到访问其中每个项目的方法,而且我无法单独设置每个下拉列表的源!这是我的打字稿代码:

@ViewChildren('messageContainer', { read: ViewContainerRef }) public messageContainer: QueryList<AutocompleteComponent>;

  @ViewChild('autocompleteComponent', { static: true }) autocompleteComponent: AutocompleteComponent;

constructor(private cfr: ComponentFactoryResolver, private _cdr: ChangeDetectorRef) { }
 GetItems() {
    this.tService.GetItemsOfTemplate().then((data) => {
      this.items = data;

      for (var i = 0; i < data.length; i++) {
        for (var j = 0; j < data[i].Items.length; j++) {
          if (data[i].Items[j].ControlType == "DDL") {            
            // Creating New Component:
                   
            this.messageContainer.changes.subscribe((list: QueryList<ViewContainerRef>) => {
              list.forEach((viewRef: ViewContainerRef, index: number) => {
                const componentFactory: ComponentFactory<any> = this.cfr.resolveComponentFactory(HisAutocompleteComponent);
                const comp = viewRef.createComponent(componentFactory, index);
               //(comp.instance as any).setData(data[i].Items[j].ItemValues, "ID", "Value");  
              });
            });

            this._cdr.detectChanges();
          }
        }
      }

      });

      this.GetValues();
      this.SetSelectedItems();
      this._cdr.detectChanges();
    });
  }

这是我的 HTML 的一部分:

<ng-container #messageContainer></ng-container>

您能否指导我生成每个自动完成并设置其数据,并帮助我了解如何访问 HTML 中的每个,然后在打字稿代码中获取选定的值(我在 autoCompleteComponent 中有一个 selectionChanged 事件。)

我阅读了所有关于 ViewChildren 的文章,但没有发现任何有用的信息。

谢谢

标签: asp.netangulartypescriptautocompleteangular-dynamic-components

解决方案


推荐阅读