首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从指令中注入物料组件?

如何从指令中注入物料组件?
EN

Stack Overflow用户
提问于 2018-08-29 17:09:06
回答 1查看 856关注 0票数 2

有没有一种方法可以使用renderer2从指令中注入material组件?

在我的例子中,我尝试创建一个指令,在一个mat-button中显示一个mat-progress-微调器。

例如,下面是一个指令。这段代码所做的事情与我正在尝试做的事情类似。由于我在项目中使用了Angular材质,所以我想添加一个名为mat-progress-spinner的材质组件,而不是这个简单的gif

代码语言:javascript
复制
@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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52073638

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档