ホームページ  >  記事  >  ウェブフロントエンド  >  angular を使用して Message コンポーネントの作成を完了する

angular を使用して Message コンポーネントの作成を完了する

亚连
亚连オリジナル
2018-06-20 15:19:421661ブラウズ

この記事では、Angular 版の Message コンポーネントの書き方を中心に紹介します。編集者が非常に良いと思ったので、参考として共有します。エディターをフォローして見てみましょう

フレームワークやライブラリを学ぶ最良の方法は、公式ドキュメントを読んでサンプルを書き始めることです。最近、空いた時間を使って Angular を学習しているので、今日はメッセージ コンポーネントを作成し、メッセージ サービスを通じてメッセージ コンポーネントを動的にロードしてみます。
私が参加しているプロジェクトは基本的にjqueryを使って完結します。以前、以下に示すように、プロジェクト内に簡単なメッセージ プラグインを自分で作成しました。

次に、angular (バージョン 5.0.0) を使用してメッセージコンポーネントを実装します。

メッセージコンポーネント

メッセージコンポーネントは、受信したタイプ、メッセージ、期間に応じて表示されます。 message.component.ts、message.component.html、message.component.css の 3 つのファイルを作成します。コードは次のとおりです。

//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

公式ドキュメントの動的コンポーネントのセクションを読むと、コンポーネントの動的作成は ComponentFactoryResolver を通じて完了する必要があることがわかります。 ComponentFactoryResolver を使用して ComponentFactory を作成し、ComponentFactory の create メソッドを通じてコン​​ポーネントを作成します。公式ドキュメントの API 説明を見ると、ComponentFactory の create メソッドには少なくとも 1 つのインジェクター パラメーターが必要であり、インジェクターの作成についてもドキュメント内で言及されており、パラメーター プロバイダーは注入する必要があるクラスです。全体のプロセスを整理しましょう:

  1. プロバイダーを提供する

  2. Injectorインスタンスを作成する

  3. ComponetFactoryを作成する

  4. ComponetFactoryを使用して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

コードを再利用するには、ここで共通のローダークラスを作成しますコンポーネントの動的作成を完了します。このうち、attch メソッドは ComponentFactory (パラメータはコンポーネントのタイプ) を初期化するために使用され、to メソッドはコンポーネントの親コンテナを識別するために使用されます。コンポーネントを作成するために使用され、手動変更検出はコンポーネントを削除するために使用されます。

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;
  }
}

同時に、ローダーの作成を容易にするために、LoaderFactory クラスを作成します。コードは次のとおりです:

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

メッセージ サービス

メッセージ サービスは、メッセージを表示するための API を提供します。コードは次のとおりです。

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

message.module

最後に、message.module.tsを追加します。動的に作成されたコンポーネントを必ずentryComponents配列に追加してください。

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{
}

使用方法

MessageServiceを注入し、APIを呼び出してMessageコンポーネントを使用します。

rreee

以上が皆さんのためにまとめたもので、今後皆さんのお役に立てれば幸いです。

関連記事:

VueコンポーネントToastにディスプレイボックスエフェクトを実装する方法

webpackのルールパラメータ処理について

AngularJSで簡単な計算を実装する方法

以上がangular を使用して Message コンポーネントの作成を完了するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。