Angular 5 attribute directive add mat-ripple to host element

醉酒当歌 提交于 2021-02-08 07:46:36

问题


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.

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.

This doesn't work.

HTML

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

Directive

@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');
  }
}

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.


回答1:


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

Directive

@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);
  }
}

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

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

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


来源:https://stackoverflow.com/questions/48221078/angular-5-attribute-directive-add-mat-ripple-to-host-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!