温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用Angular CDK实现一个Service弹出Toast组件功能

发布时间:2021-07-28 11:11:14 来源:亿速云 阅读:128 作者:小新 栏目:开发技术

这篇文章将为大家详细讲解有关如何使用Angular CDK实现一个Service弹出Toast组件功能,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

1.环境安装

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.创建Toast组件和ToastService

  • 使用ng g c Toast命令快速创建一个组件模版

  • 使用ng g s Toast创建一个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的组件的构造方法写上对应的ToastService就可以正常运行了。

export class AppComponent {
  constructor(private toast:ToastService) {
  }
  test() {

    this.toast.Show('hello cdk!')
  }
}

gif效果图

如何使用Angular CDK实现一个Service弹出Toast组件功能

关于“如何使用Angular CDK实现一个Service弹出Toast组件功能”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI