这篇文章将为大家详细讲解有关如何使用Angular CDK实现一个Service弹出Toast组件功能,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
cdk不是angular的默认模块,需要手动安装 yarn add @angular/cdk
在app.module中引入cdk中的OverlayModule
import { OverlayModule } from '@angular/cdk/overlay';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
OverlayModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
使用ng g c Toast
命令快速创建一个组件模版
使用ng g s Toast
创建一个Service的模版
ToastComponent
<div class="q-toast">
<div class="q-toast-mask"></div>
<p class="q-toast-msg">{{msg}}</p>
</div>
.q-toast {
padding: .2rem .5rem;
width: 5rem;
position: relative;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
.q-toast-mask {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #000;
opacity: .8;
border-radius: 2rem;
}
.q-toast-msg {
color: white;
z-index: 999;
}
}
ToastService
import { Overlay, OverlayConfig } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';
import { Injectable, InjectionToken, Injector } from '@angular/core';
import { ToastComponent } from './toast.component';
@Injectable({
providedIn: 'root'
})
export class ToastService {
constructor(private overlay: Overlay) { }
Show(msg: string) {
const config = new OverlayConfig();
const positionStrategy = this.overlay.position()
.global().centerVertically().centerHorizontally();
config.positionStrategy = positionStrategy;
let overlayRef = this.overlay.create(config);
const inject = Injector.create({
providers: [
{
provide: Toast_Ref,
useValue: overlayRef
},
{
provide: Toast_Msg,
useValue: msg
}
]
})
console.log(inject.get<string>(Toast_Ref))
let partal = new ComponentPortal(ToastComponent, null, inject);
overlayRef.attach(partal)
setTimeout(() => {
overlayRef.detach()
overlayRef.dispose();
}, 2000);
}
}
export const Toast_Ref = new InjectionToken<{}>('Toast_Ref');
export const Toast_Msg = new InjectionToken<{}>('Toast_Msg');
使用Toast
编写好Service后,只需要Angular会默认注入到root模块,只需要在需要弹出Toast的组件的构造方法写上对应的ToastService就可以正常运行了。
export class AppComponent {
constructor(private toast:ToastService) {
}
test() {
this.toast.Show('hello cdk!')
}
}
gif效果图
关于“如何使用Angular CDK实现一个Service弹出Toast组件功能”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。