有没有一种方法可以使用renderer2从指令中注入material组件?
在我的例子中,我尝试创建一个指令,在一个mat-button中显示一个mat-progress-微调器。
例如,下面是一个指令。这段代码所做的事情与我正在尝试做的事情类似。由于我在项目中使用了Angular材质,所以我想添加一个名为mat-progress-spinner的材质组件,而不是这个简单的gif
@Directive({
selector: '[appButtonLoader]'
})
export class ButtonLoaderDirective {
img: HTMLImageElement;
@Input() set appButtonLoader(value: boolean) {
this.toggle(value);
}
constructor(private element:ElementRef) {
this.img = document.createElement('img');
this.img.src = 'https://www.winston.com/cached/40181/images/spinner-white.gif';
this.toggle(this.appButtonLoader);
}
toggle(condition: boolean) {
condition ? this.show() : this.hide()
}
show() {
this.element.nativeElement.appendChild(this.img);
}
hide() {
this.img.remove();
}}
stackblitz:https://stackblitz.com/edit/load-button-directive?file=app%2Fbutton-loader.directive.ts
发布于 2018-08-29 23:30:46
此处提供的解决方案:https://angular.io/guide/dynamic-component-loader
在我的例子中,这是不够的,因为垫按钮不是一个ViewContainerRef,所以我不能createComponent。
最后的解决方案是createComponent,然后用Renderer2.appendChild移动它
Stackblitz更新:https://stackblitz.com/edit/load-button-directive?file=app%2Fbutton-loader2.directive.ts
https://stackoverflow.com/questions/52073638
复制相似问题