这篇文章将为大家详细讲解有关如何使用angular CDK实现一个Service弹出Toast组件功能,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。1.环境安装cdk不是angular的默认模块,需要手动
这篇文章将为大家详细讲解有关如何使用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组件功能”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
--结束END--
本文标题: 如何使用Angular CDK实现一个Service弹出Toast组件功能
本文链接: https://www.lsjlt.com/news/298891.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0