问题
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