angular - 如何将按钮动态注入 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)
});
问题:
- 上面的代码注入了原始 HTML。它未编译为应用 Material UI。
- 另外,当我们点击按钮时,它的上下文是无效的,无法调用 registerWord() 函数。
** 截屏:**
预先感谢您的帮助!
真诚的,亚历克斯
解决方案
这是在 Angular 中动态显示和隐藏元素的一种不好的方法,如果您没有充分的理由这样做,则应避免使用它。
顺便说一句,您在一个临时模块中声明了您的组件,但该模块尚未导入MatButtonModule
,因此 Angular 无法解析指令。
MatButtonModule
在您的临时模块中导入:
const tmpModule = NgModule({
imports: [MatButtonModule],
declarations: [tmpCmp],
entryComponents: [tmpCmp]})
(class {});
推荐阅读
- javascript - 如何在 JSX div 的 id 中添加 if 条件?
- swift - 如何在功能字段中使用父级?
- database-design - sql中的存储技术
- hibernate - 如何用 JPA 和 hibernate 管理一个简单的博客表结构?
- python - 根据 ID 状态转换数据帧
- javascript - 检查数组是否为空时,我应该使用 array.length <= 0 还是 array.length === 0?
- sorting - 在记事本++中的某个字符之后对行进行排序
- python - Holoviews:如何将多个 RGB 图像包装到数据集中并正确显示它们?
- python - 如何在烧瓶中一一处理请求?
- db2 - 连接到 DB2 客户端,Toad 没有找到默认的 64 位 db2 客户端