时间:2023-02-27 10:33:59 | 栏目:AngularJS | 点击:次
在Angular中,官方团队在开发Material组件库的同时,顺手做了一套Component dev kit,也就是在Angular世界中大名鼎鼎的CDK,这套工具包提供了非常多的前端开发的通用功能。Angular的知名组件库几乎都依赖了这套开发包。比如ANT,PrimeNG等。
本文主要写用cdk实现一个简单的Toast组件,使用的是cdk中的overlay模块。
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效果图