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

What is flex and a detailed tutorial on flex layout syntax

Flex Layout Flex is the abbreviation of Flexible ...

Calling the search engine in the page takes Baidu as an example

Today, it suddenly occurred to me that it would be...

How to install MySQL under Linux (yum and source code compilation)

Here are two ways to install MySQL under Linux: y...

Horizontal header menu implemented with CSS3

Result:Implementation Code html <nav class=&qu...

MySQL complete collapse query regular matching detailed explanation

Overview In the previous chapter, we learned abou...

SQL uses ROW_NUMBER() OVER function to generate sequence number

Syntax: ROW_NUMBER() OVER(PARTITION BY COLUMN ORD...

How to monitor the running status of docker container shell script

Scenario The company project is deployed in Docke...

How to draw the timeline with vue+canvas

This article example shares the specific code of ...

A brief introduction to the usage of decimal type in MySQL

The floating-point types supported in MySQL are F...

WeChat applet to achieve the revolving lantern effect example

Preface In daily development, we often encounter ...

mysql group by grouping multiple fields

In daily development tasks, we often use MYSQL...

Docker network mode and configuration method

1. Docker Network Mode When docker run creates a ...

Detailed explanation of Javascript string methods

Table of contents String length: length charAt() ...

Using Docker+jenkins+python3 environment to build a super detailed tutorial

Preface: After the automation is written, it need...