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

问题描述 投票:1回答:1

如何将mat-ripple指令添加到我创建的自定义指令的host元素中?关键是要将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直接添加到元素时相同的颜色。

angular angular-directive
1个回答
5
投票

通过在指令中提供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>
© www.soinside.com 2019 - 2024. All rights reserved.