這篇文章主要介紹如何實現(xiàn)一個angular版本的Message組件,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
成都創(chuàng)新互聯(lián)公司是一家專業(yè)提供廣德企業(yè)網(wǎng)站建設,專注與成都網(wǎng)站建設、成都網(wǎng)站制作、HTML5建站、小程序制作等業(yè)務。10年已為廣德眾多企業(yè)、政府機構等服務。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站設計公司優(yōu)惠進行中。學習一個框架或庫的最好方法是看官方文檔,并著手去寫例子。最近在利用空閑的時間學習angular,那今天就嘗試寫一個message組件,并通過message服務動態(tài)加載message組件。
我所參與的項目基本是用jquery完成的。之前,在項目中自己動手寫過一個簡單的message插件,樣子如下圖。

那現(xiàn)在就使用angular(版本5.0.0)來實現(xiàn)message組件。
message組件
message組件要根據(jù)傳入的類型、消息和duration來顯示。創(chuàng)建三個文件:message.component.ts,message.component.html,message.component.css,代碼如下。
//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-->
<div class="upc-message">
<div class="upc-message-content" [ngClass]="typeClass">
<i class="glyphicon" [ngClass]="typeIconClass"></i>
{{payload}}
</div>
</div>.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
通過官方文檔動態(tài)組件一節(jié),可以了解動態(tài)創(chuàng)建組件需要通過ComponentFactoryResolver來完成。使用ComponentFactoryResolver創(chuàng)建ComponentFactory,再通過ComponentFactory的create方法創(chuàng)建組件。看官方文檔中API的說明,ComponentFactory的create方法至少需要一個injector參數(shù),而injector的創(chuàng)建在文檔中也有提到,其中參數(shù)providers為需要注入的類。再梳理下整個過程:
提供providers
創(chuàng)建Injector實例
創(chuàng)建ComponetFactory
使用ComponetFactory創(chuàng)建ComponentRef
//ComponentFactory的create方法 create(injector: Injector, projectableNodes?: any[][], rootSelectorOrNode?: string|any, ngModule?: NgModuleRef<any>): ComponentRef<C> //使用Injector的create創(chuàng)建injector實例 static create(providers: StaticProvider[], parent?: Injector): Injector
為了代碼的復用,這里創(chuàng)建通用的loader類來完成組件的動態(tài)創(chuàng)建。其中,attch方法用于初始化ComponetFactory(參數(shù)為組件類型);to方法用于標識組件的父容器;provider方法用于初始化可注入的類;create方法用于創(chuàng)建組件并手動變更檢測;remove方法用于移除組件。
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;
}
}同時,為了便于loader的創(chuàng)建,再創(chuàng)建LoaderFactory類,代碼如下:
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提供顯示message的API,代碼如下:
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
最后,增加message.module.ts。記得要把動態(tài)創(chuàng)建的組件添加到entryComponents數(shù)組中。
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{
}使用方法
注入MessageService,調用API使用Message組件。
this._msgService.success('成功了!');以上是“如何實現(xiàn)一個angular版本的Message組件”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關知識,歡迎關注創(chuàng)新互聯(lián)成都網(wǎng)站設計公司行業(yè)資訊頻道!
另外有需要云服務器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
文章題目:如何實現(xiàn)一個angular版本的Message組件-創(chuàng)新互聯(lián)
本文URL:http://chinadenli.net/article34/ccippe.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站、營銷型網(wǎng)站建設、網(wǎng)站制作、網(wǎng)站設計、外貿(mào)網(wǎng)站建設、網(wǎng)站改版
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容