Angular 5 属性指令将 mat-ripple 添加到宿主元素

Angular 5 attribute directive add mat-ripple to host element

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

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

这行不通。

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 通过模板直接添加到元素。

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

指令

@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; 样式以防止波纹扩展到按钮之外。

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

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