本文介绍了Angular 5 属性指令将 mat-ripple 添加到宿主元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 mat-ripple 指令添加到我创建的自定义指令的宿主元素?关键是让 mat-ripple 自动添加到我添加了 my-custom-directive 的任何元素中.

How can I add the mat-ripple directive to the host element of a custom directive I've created? The point is to have mat-ripple automagically added to any element I add my-custom-directive too.

因此,如果我将 添加到模板中,它应该呈现为 而不必每次使用 my-custom-directive 时都输入所有内容.作为一个例子,看看 mat-raised-button 是如何工作的.您只需添加该指令即可获得 mat-ripple .我想用我自己的按钮复制它.

So if I add <button my-custom-directive>Button</button> to the template it should be rendered as <button my-custom-directive mat-ripple mat-ripple-color="#000">Button</button> without having to type all of that out every time I use my-custom-directive. As an example look at how mat-raised-button works. You simply add that directive and you get mat-ripple with it. I want to duplicate that with my own buttons.

这不起作用.

HTML

<button my-custom-directive>Button</button>

指令

@Directive({
  selector: ['appMyCustomDirective']
})
export class MyCustomDirective implements AfterViewInit {
  constructor(
    private renderer: Renderer,
    private element: ElementRef
  ) { }

  ngAfterViewInit() {
    this.renderer.setElementAttribute(this.element.nativeElement, 'mat-ripple', '');
    this.renderer.setElementAttribute(this.element.nativeElement, 'mat-ripple-color', '#000000');
  }
}

我还尝试将 MatRipple 注入指令并调用 MatRipple.launch(...) 但这会产生不受按钮内约束的涟漪效果,并且不应用与我通过模板将 mat-ripple 直接添加到元素时相同的颜色.

I also tried injecting MatRipple into the directive and calling MatRipple.launch(...) but this creates a ripple effect that isn't constrained inside the button and doesn't apply the same colors as when I add mat-ripple directly to the element via the template.

推荐答案

我能够通过在指令中提供 MatRipple 并结合一些样式手动启动来实现我的目标.

I was able to achieve my goal by providing MatRipple in the directive and manually launching combined with some styles.

指令

@Directive({
  selector: '[app-outline-button]',
  providers: [ MatRipple ]
})
export class OutlineButtonDirective implements AfterViewInit {
  constructor(
    private ripple: MatRipple
  ) { }

  @HostListener('mousedown', [ '$event' ]) onmousedown(event) {
    this.ripple.launch(event.x, event.y);
  }
}

然后我不得不给按钮 overflow: hidden; 样式以防止涟漪扩展到按钮之外.

I then had to give the button overflow: hidden; style to prevent the ripple from expanding beyond the button.

最后使用我的指令,它自动神奇地包含 mat-ripple 指令:

Finally to use my directive which auto-magically includes mat-ripple directive:

<button app-outline-button>Button</button>

这篇关于Angular 5 属性指令将 mat-ripple 添加到宿主元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:36