首页 > 解决方案 > 如何将按钮动态注入 Angular 6 应用程序?

问题描述

我正在使用一个组件构建一个 Web 应用程序,该组件根据从 API 接收的数据显示 Material UI 按钮。

工作流程:

我正在尝试构建的组件的工作流程如下:

(1)页面加载完毕,调用API从后端接收30个随机词,前三个词以按钮的形式展示给用户

(2)用户点击一个词。其他两个然后自动禁用。以下三个单词被选择并显示/注入为页面上的新按钮。

(3)当30个词都显示给用户后,下一次点击再检索30个,这个过程无限期地继续下去。

动态生成这些按钮并将它们插入 UI 的最佳方法是什么?

以下是到目前为止我的代码片段。虽然,如果有人有更好的方法,我很乐意使用它!:)

数据样本:

["word1", "word2", "word3", …, "word30"]

模板:

 this.templateButtonRow$ = `
      <div class="button-row">
        <button mat-raised-button (click)="registerWord(WORD)">
          WORD
        </button>
      </div>`;

注入代码:

@ViewChild('buttonrows', {read: ViewContainerRef}) vc: ViewContainerRef;
…
const tmpCmp = Component({template: this.templateButtonRow$})(class {});
  const tmpModule = NgModule({declarations: [tmpCmp], entryComponents: [tmpCmp]})(class {});
  this._compiler.compileModuleAndAllComponentsAsync(tmpModule)
    .then((factories) => {
      const f = factories.componentFactories[0];
      const cmpRef = f.create(this._injector, [], null, this._m);
      cmpRef.instance.name = 'B component';
      this.vc.insert(cmpRef.hostView)
    });

问题:

** 截屏:**

在此处输入图像描述

预先感谢您的帮助!

真诚的,亚历克斯

标签: angularangular-material

解决方案


这是在 Angular 中动态显示和隐藏元素的一种不好的方法,如果您没有充分的理由这样做,则应避免使用它。

顺便说一句,您在一个临时模块中声明了您的组件,但该模块尚未导入MatButtonModule,因此 Angular 无法解析指令。

MatButtonModule在您的临时模块中导入:

const tmpModule = NgModule({
  imports: [MatButtonModule], 
  declarations: [tmpCmp], 
  entryComponents: [tmpCmp]})
  (class {});

推荐阅读