【问题标题】:How to inject material component from a directive?如何从指令中注入材料组件?
【发布时间】:2019-02-04 00:26:02
【问题描述】:

有没有办法使用 renderer2 从指令中注入材质组件?

在我的例子中,我尝试制定一个指令,在 mat-button 中显示 mat-progress-spinner。

例如,这是一个指令。这段代码正在做类似于我正在尝试做的事情。由于我在我的项目中使用 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

【问题讨论】:

  • 为了提高您问题的可读性而进行的小改动。但我建议你自己尝试一下,而不是添加一些minimal reproducible example。与“这里有一个要求,怎么做”风格的问题相比,包含“自己的努力”的问题通常会收到更多有用的反馈。
  • 问题已编辑

标签: angular-material


【解决方案1】:

在这里找到解决方案:https://angular.io/guide/dynamic-component-loader

就我而言,这还不够,因为 Mat-Button 不是 ViewContainerRef,所以我无法创建组件。

最终的解决方案是创建组件,然后使用 Renderer2.appendChild 移动它

Stackblitz 更新:https://stackblitz.com/edit/load-button-directive?file=app%2Fbutton-loader2.directive.ts

【讨论】:

  • 很棒的工作伙伴,正是我想要的 :)(对问题和答案都投了赞成票)
猜你喜欢
  • 1970-01-01
  • 2020-12-03
  • 1970-01-01
  • 1970-01-01
  • 2019-01-07
  • 1970-01-01
  • 2021-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多