使用Angular CDK實現(xiàn)一個Service彈出Toast組件功能
在Angular中,官方團隊在開發(fā)Material組件庫的同時,順手做了一套Component dev kit,也就是在Angular世界中大名鼎鼎的CDK,這套工具包提供了非常多的前端開發(fā)的通用功能。Angular的知名組件庫幾乎都依賴了這套開發(fā)包。比如ANT,PrimeNG等。
本文主要寫用cdk實現(xiàn)一個簡單的Toast組件,使用的是cdk中的overlay模塊。
1.環(huán)境安裝
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 { }
2.創(chuàng)建Toast組件和ToastService
- 使用
ng g c Toast
命令快速創(chuàng)建一個組件模版 - 使用
ng g s Toast
創(chuàng)建一個Service的模版
2.1編寫Toast組件和樣式
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的組件的構(gòu)造方法寫上對應(yīng)的ToastService就可以正常運行了。
export class AppComponent { constructor(private toast:ToastService) { } test() { this.toast.Show('hello cdk!') } }
gif效果圖
到此這篇關(guān)于使用Angular CDK實現(xiàn)一個Service彈出Toast組件的文章就介紹到這了,更多相關(guān)Angular CDK 實現(xiàn)Toast組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
div實現(xiàn)自適應(yīng)高度的textarea實現(xiàn)angular雙向綁定
本文主要介紹了div實現(xiàn)自適應(yīng)高度的textarea,實現(xiàn)angular雙向綁定的方法。具有一定的參考價值,下面跟著小編一起來看下吧2017-01-01AngularJS 與Bootstrap實現(xiàn)表格分頁實例代碼
這篇文章主要介紹了AngularJS 與Bootstrap實現(xiàn)表格分頁的相關(guān)資料,并附實例代碼和實現(xiàn)效果圖,需要的朋友可以參考下2016-10-10Angular+ionic實現(xiàn)折疊展開效果的示例代碼
這篇文章主要介紹了Angular+ionic實現(xiàn)折疊展開效果,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07