gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:41:42 27 4
gpt4 key购买 nike

如何添加 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');
}
}

我也试过注入(inject) 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>

关于Angular 5 属性指令将 mat-ripple 添加到主机元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48221078/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com