我需要添加一个具有Material Angular 2样式的按钮。所以我有一个按钮可以做到这一点:
<button mat-button (click)="addElement($event, 'button')">Add button</button>
其中定义了addElement:
addElement(ev, tag) {
const htmlElem = ev.currentTarget;
const el = this.renderer.createElement(tag);
this.renderer.setAttribute(el, 'mat-button', '');
el.textContent = 'New Button';
htmlElem.parentNode.insertBefore(el, null);
}
单击按钮,然后在我的HTML中创建一个新元素,如下所示:
<button mat-button">Add button</button>
功能代码可以正确生成按钮,但是并不能应用所有子元素,如物料代码中的原始按钮代码所示
那么,我是否有办法“刷新”按钮,以便标准Mat按钮的所有内容都适用于通过JS代码添加的按钮?
我不确定为什么要动态生成按钮,但是我会这样做
在您的模板中:
<button mat-raised-button (click)="addNewButton()">Add new </button>
<div *ngFor="let btn of buttonsList">
<button mat-raised-button color="primary">
{{btn+1}}
</button>
</div>
在您的组件中:
export class AppComponent {
buttonsList = [];
addNewButton():void{
const newId = this.buttonsList.length;
this.buttonsList.push(newId);
}
}
您只需要遍历数组并显示按钮。每次添加新按钮时,只需将新值推入数组,然后让框架进行繁重的工作即可。
这是stackblitz演示:https ://stackblitz.com/edit/angular-7rfwrx ? file = app%2Fapp.component.ts
希望这可以帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句