Use Angular CDK to implement a Service pop-up Toast component function

Use Angular CDK to implement a Service pop-up Toast component function

In Angular, while developing the Material component library, the official team also developed a Component dev kit, which is the famous CDK in the Angular world. This toolkit provides many common functions for front-end development. Almost all well-known Angular component libraries rely on this development kit. Such as ANT, PrimeNG, etc.

This article mainly uses CDK to implement a simple Toast component, using the overlay module in CDK.

1. Environmental Installation

cdk is not a default module of angular, you need to install it manually yarn add @angular/cdk

Introduce OverlayModule in cdk in app.module

import { OverlayModule } from '@angular/cdk/overlay';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    OverlayModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

2. Create Toast components and ToastService

  • Use ng gc Toast command to quickly create a component template
  • Use ng gs Toast to create a Service template

2.1 Write Toast components and styles

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');

Using Toast

After writing the Service, Angular will inject it into the root module by default. You only need to write the corresponding ToastService in the construction method of the component where Toast needs to pop up, and it will run normally.

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

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

GIF effect picture

This is the end of this article about using Angular CDK to implement a Service pop-up Toast component. For more information about Angular CDK implementing the Toast component, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed steps to implement drag and drop of page elements through angular CDK
  • Use Angular material theme to define the color scheme of your component library
  • Angular6 develops steps bar component
  • Angular 2 uses routing to customize the pop-up component toast operation example
  • Angular2 uses SVG to customize chart (bar chart, line chart) component example
  • Angular encapsulated search box component operation example

<<:  Solution to Linux not supporting all commands

>>:  Steps to initialize the password after the first successful installation of MySQL

Recommend

Vue+Element realizes paging effect

This article example shares the specific code of ...

How to read the regional information of IP using Nginx and GeoIP module

Install GeoIP on Linux yum install nginx-module-g...

Complete steps to set up automatic updates in CentOS 8

The best thing you can do for your data and compu...

HTML+CSS to create heartbeat special effects

Today we are going to create a simple heartbeat e...

How to implement horizontal bar chart with percentage in echarts

Table of contents Example Code Rendering Code Ana...

Modify file permissions (ownership) under Linux

Linux and Unix are multi-user operating systems, ...

Detailed explanation of Vue custom instructions

Table of contents Vue custom directive Custom dir...

Detailed explanation of Nginx Rewrite usage scenarios and code examples

Nginx Rewrite usage scenarios 1. URL address jump...

How to keep running after exiting Docker container

Phenomenon: Run an image, for example, ubuntu14.0...

How to process blob data in MySQL

The specific code is as follows: package epoint.m...

MySQL high availability solution MMM (MySQL multi-master replication manager)

1. Introduction to MMM: MMM stands for Multi-Mast...

MySQL database master-slave replication and read-write separation

Table of contents 1. Master-slave replication Mas...

Notes on MySQL case sensitivity

Table of contents MySQL case sensitivity is contr...