Home > Web Front-end > JS Tutorial > Complete the writing of Message component using angular

Complete the writing of Message component using angular

亚连
Release: 2018-06-20 15:19:42
Original
1725 people have browsed it

This article mainly introduces how to write an angular version of the Message component. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

The best way to learn a framework or library is to read the official documentation and start writing examples. I have been using my free time to learn Angular recently, so today I will try to write a message component and dynamically load the message component through the message service.
The projects I participate in are basically completed with jquery. Previously, I wrote a simple message plug-in myself in the project, as shown below.

Now use angular (version 5.0.0) to implement the message component.

message component

The message component should be displayed according to the incoming type, message and duration. Create three files: message.component.ts, message.component.html, message.component.css, the code is as follows.

//message.component.ts
import {Component,Input,OnInit,ChangeDetectionStrategy} from '@angular/core';
import {
  trigger,
  state,
  style,
  transition,
  animate
 } from '@angular/animations';
const mapping={
  success:'glyphicon-ok-sign',
  warning:'glyphicon-exclamation-sign',
  error:'glyphicon-exclamation-sign',
  info:'glyphicon-ok-circle'
}
@Component({
  selector:'upc-ng-message',
  templateUrl:'./message.component.html',
  styleUrls:['./message.component.css'],
  changeDetection:ChangeDetectionStrategy.OnPush
})
export class MessageComponent implements OnInit{
  ngOnInit(): void {
    this.typeClass=['upc-message-' + this.msgType];
    this.typeIconClass=[mapping[this.msgType]];
  }
  @Input() msgType:'success' | 'info' | 'warning' | 'error'='info'

  @Input() payload:string = ''

  private typeClass
  private typeIconClass
}
Copy after login
<!--*message.component.html-->
<p class="upc-message">
    <p class="upc-message-content" [ngClass]="typeClass">
      <i class="glyphicon" [ngClass]="typeIconClass"></i>
      {{payload}}
    </p>
</p>
Copy after login
.upc-message {
  position: fixed;
  z-index: 1999;
  width: 100%;
  top: 36px;
  left: 0;
  pointer-events: none;
  padding: 8px;
  text-align: center;
 }
 .upc-message i {
   margin-right: 8px;
   font-size: 14px;
   top: 1px;
   position: relative;
 }
 .upc-message-success i {
   color: green;
 }
 .upc-message-warning i {
   color: yellow;
 }
 .upc-message-error i {
   color: red;
 }
 .upc-message-content {
   padding: 8px 16px;
   -ms-border-radius: 4px;
   border-radius: 4px;
   -webkit-box-shadow: 0 2px 8px #000000;
   -ms-box-shadow: 0 2px 8px #000000;
   box-shadow: 0 2px 8px #000000;
   box-shadow: 0 2px 8px rgba(0,0,0,.2);
   background: #fff;
   display: inline-block;
   pointer-events: all;
 }
Copy after login

ComponentLoader

Through the dynamic components section of the official document, you can understand that dynamically creating components needs to be completed through ComponentFactoryResolver. Use ComponentFactoryResolver to create a ComponentFactory, and then create components through the create method of ComponentFactory. Looking at the API description in the official document, the create method of ComponentFactory requires at least one injector parameter, and the creation of the injector is also mentioned in the document, where the parameter providers is the class that needs to be injected. Let’s sort out the whole process:

  1. Provide providers

  2. Create Injector instance

  3. Create ComponentFactory

  4. Use ComponentFactory to create ComponentRef

//ComponentFactory的create方法
create(injector: Injector, projectableNodes?: any[][], rootSelectorOrNode?: string|any, ngModule?: NgModuleRef<any>): ComponentRef<C>

//使用Injector的create创建injector实例
static create(providers: StaticProvider[], parent?: Injector): Injector
Copy after login

For code reuse, a general loader class is created here to complete the dynamic creation of components. Among them, the attch method is used to initialize the ComponentFactory (the parameter is the component type); the to method is used to identify the parent container of the component; the provider method is used to initialize the injectable class; the create method is used to create components and manual change detection; the remove method is used to Remove components.

import {
  ComponentFactoryResolver,
  ComponentFactory,
  ComponentRef,
  Type,
  Injector,
  Provider,
  ElementRef
} from &#39;@angular/core&#39;;
export class ComponentLoader<T>{
  constructor(private _cfr: ComponentFactoryResolver,
    private _injector: Injector) {
  }
  private _componentFactory: ComponentFactory<T>
  attch(componentType: Type<T>): ComponentLoader<T> {
    this._componentFactory = this._cfr.resolveComponentFactory<T>(componentType);
    return this;
  }
  private _parent: Element
  to(parent: string | ElementRef): ComponentLoader<T> {
    if (parent instanceof ElementRef) {
      this._parent = parent.nativeElement;
    } else {
      this._parent = document.querySelector(parent);
    }

    return this;
  }
  private _providers: Provider[] = [];
  provider(provider: Provider) {
    this._providers.push(provider);
  }
  create(opts: {}): ComponentRef<T> {
    const injector = Injector.create(this._providers as any[], this._injector);
    const componentRef = this._componentFactory.create(injector);
    Object.assign(componentRef.instance, opts);
    if (this._parent) {
      this._parent.appendChild(componentRef.location.nativeElement);
    }
    componentRef.changeDetectorRef.markForCheck();
    componentRef.changeDetectorRef.detectChanges();
    return componentRef;
  }
  remove(ref:ComponentRef<T>){
    if(this._parent){
      this._parent.removeChild(ref.location.nativeElement)
    }
    ref=null;
  }
}
Copy after login

At the same time, in order to facilitate the creation of loader, create the LoaderFactory class, the code is as follows:

import {
  ComponentFactoryResolver,
  Injector,
  Injectable,
  ElementRef
} from &#39;@angular/core&#39;;
import { ComponentLoader } from &#39;./component-loader.class&#39;;

@Injectable()
export class ComponentLoaderFactory {
  constructor(private _injector: Injector,
    private _cfr: ComponentFactoryResolver) {

  }

  create<T>(): ComponentLoader<T> {
    return new ComponentLoader(this._cfr, this._injector);
  }
}
Copy after login

message service

message service provides display of message API, the code is as follows:

import {Injectable,Injector} from &#39;@angular/core&#39;;
import { ComponentLoaderFactory } from &#39;../component-loader/component-loader.factory&#39;;
import {MessageComponent} from &#39;./message.component&#39;;
import {ComponentLoader} from &#39;../component-loader/component-loader.class&#39;;

@Injectable()
export class MessageService{
  constructor(private _clf:ComponentLoaderFactory,private _injector:Injector){
    this.loader=this._clf.create<MessageComponent>();
  }
  private loader:ComponentLoader<MessageComponent>
  private createMessage(t,c,duration=2000){
    this.loader.attch(MessageComponent).to(&#39;body&#39;);
    const opts = {
      msgType: t,
      payload:c
    };
    const ref = this.loader.create(opts);
    ref.changeDetectorRef.markForCheck();
    ref.changeDetectorRef.detectChanges();
    let self=this;
    let st = setTimeout(() => {
      self.loader.remove(ref);
    }, duration);
  }
  public info(payload,duration?) {
    this.createMessage(&#39;info&#39;,payload,duration);
  }
  public success(payload,duration?) {
    this.createMessage(&#39;success&#39;,payload,duration);
  }
  public error(payload,duration?) {
    this.createMessage(&#39;error&#39;,payload,duration);
  }
  public warning(payload,duration?) {
    this.createMessage(&#39;warning&#39;,payload,duration);
  }
}
Copy after login

message.module

Finally, add message.module.ts. Remember to add dynamically created components to the entryComponents array.

import {NgModule} from &#39;@angular/core&#39;;
import { CommonModule } from &#39;@angular/common&#39;;
import {MessageComponent} from &#39;./message.component&#39;;
import {MessageService} from &#39;./message.service&#39;;
import {ComponentLoaderFactory} from &#39;../component-loader/component-loader.factory&#39;;

@NgModule({
  imports:[CommonModule],
  declarations:[MessageComponent],
  providers:[MessageService,ComponentLoaderFactory],
  entryComponents:[MessageComponent],
  exports:[MessageComponent]
})
export class MessageModule{
}
Copy after login

Use method

Inject MessageService and call the API to use the Message component.

this._msgService.success(&#39;成功了!&#39;);
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to achieve the display box effect in the Vue component Toast

About rules parameter processing in webpack

How to implement simple calculations in AngularJS

The above is the detailed content of Complete the writing of Message component using angular. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template