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 }
<!--*message.component.html--> <p class="upc-message"> <p class="upc-message-content" [ngClass]="typeClass"> <i class="glyphicon" [ngClass]="typeIconClass"></i> {{payload}} </p> </p>
.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; }
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:
Provide providers
Create Injector instance
Create ComponentFactory
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
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 '@angular/core'; 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; } }
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 '@angular/core'; import { ComponentLoader } from './component-loader.class'; @Injectable() export class ComponentLoaderFactory { constructor(private _injector: Injector, private _cfr: ComponentFactoryResolver) { } create<T>(): ComponentLoader<T> { return new ComponentLoader(this._cfr, this._injector); } }
message service
message service provides display of message API, the code is as follows:
import {Injectable,Injector} from '@angular/core'; import { ComponentLoaderFactory } from '../component-loader/component-loader.factory'; import {MessageComponent} from './message.component'; import {ComponentLoader} from '../component-loader/component-loader.class'; @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('body'); 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('info',payload,duration); } public success(payload,duration?) { this.createMessage('success',payload,duration); } public error(payload,duration?) { this.createMessage('error',payload,duration); } public warning(payload,duration?) { this.createMessage('warning',payload,duration); } }
message.module
Finally, add message.module.ts. Remember to add dynamically created components to the entryComponents array.
import {NgModule} from '@angular/core'; import { CommonModule } from '@angular/common'; import {MessageComponent} from './message.component'; import {MessageService} from './message.service'; import {ComponentLoaderFactory} from '../component-loader/component-loader.factory'; @NgModule({ imports:[CommonModule], declarations:[MessageComponent], providers:[MessageService,ComponentLoaderFactory], entryComponents:[MessageComponent], exports:[MessageComponent] }) export class MessageModule{ }
Use method
Inject MessageService and call the API to use the Message component.
this._msgService.success('成功了!');
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!