出了什么问题?
您是对的,您添加了 mat-button 属性,但是由于您是动态创建按钮,因此无法实现生成 mat-button 的整个结构。
下面是mat-button的整体风格和结构
<button class="mat-button" mat-button="">
<span class="mat-button-wrapper">Add button</span>
<div class="mat-button-ripple mat-ripple"></div>
<div class="mat-button-focus-overlay"></div>
</button>
如您所见,mat-button 中还有其他 html 元素,包括波纹效果和焦点覆盖。
您的问题的解决方案
我们将使用 Angular Renderer 创建 html 元素,将属性设置为元素并将其附加到元素上。
所以我们做了什么
创建将触发追加的按钮
<button id="clickBtn" (click)="onClick()">Click here to add Button</button>
在组件中导入import Directive, ElementRef, Renderer2。
{ Component, Directive, ElementRef, Renderer2 } from '@angular/core';
添加一个指令,该指令将针对将附加按钮的 html 元素(#clickBtn [是我们创建的按钮的 id 标签)
@Directive({
selector: '#clickBtn'
})
创建一个构造函数来注入渲染器和元素引用
constructor(private renderer: Renderer2,private elRef: ElementRef) {
}
触发点击事件追加按钮
onClick() {
const btn = this.renderer.createElement('button');
const span = this.renderer.createElement('span');
const div1 = this.renderer.createElement('div');
const div2 = this.renderer.createElement('div');
const text = this.renderer.createText('I am a Generated Button');
const attrBtn = this.renderer.setAttribute(btn, 'class', 'mat-button');
const attrSpan = this.renderer.setAttribute(span, 'class', 'mat-button-wrapper');
const attrDiv1 = this.renderer.setAttribute(div1, 'class', 'mat-button-ripple mat-ripple');
const attrDiv2 = this.renderer.setAttribute(div2, 'class', 'mat-button-focus-overlay');
this.renderer.appendChild(span, text);
this.renderer.appendChild(btn, span);
this.renderer.appendChild(btn, div1);
this.renderer.appendChild(btn, div2);
this.renderer.appendChild(this.elRef.nativeElement, btn);
}
哇,这里发生了什么。如您所见,我们在这里生成了 mat-button 的所有结构
要了解有关 Renderer2 的更多信息,请访问此链接。
https://alligator.io/angular/using-renderer2/
请看stackblitz上实时代码的链接
https://stackblitz.com/edit/dmgrave-ng-so-answer-dom?file=app%2Fapp.component.ts
希望这会有所帮助。