angular を使用して Message コンポーネントの作成を完了する
この記事では、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 つのインジェクター パラメーターが必要であり、インジェクターの作成についてもドキュメント内で言及されており、パラメーター プロバイダーは注入する必要があるクラスです。全体のプロセスを整理しましょう:
プロバイダーを提供する
Injectorインスタンスを作成する
ComponetFactoryを作成する
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 '@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; } }
同時に、ローダーの作成を容易にするために、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); } }
メッセージ サービス
メッセージ サービスは、メッセージを表示するための 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を追加します。動的に作成されたコンポーネントを必ずentryComponents配列に追加してください。
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コンポーネントを使用します。
rreee以上が皆さんのためにまとめたもので、今後皆さんのお役に立てれば幸いです。
関連記事:
VueコンポーネントToastにディスプレイボックスエフェクトを実装する方法
以上がangular を使用して Message コンポーネントの作成を完了するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











この記事では、Angular の学習を継続し、Angular のメタデータとデコレータを理解し、それらの使用法を簡単に理解します。

Angular.js は、動的アプリケーションを作成するための無料でアクセスできる JavaScript プラットフォームです。 HTML の構文をテンプレート言語として拡張することで、アプリケーションのさまざまな側面を迅速かつ明確に表現できます。 Angular.js は、コードの作成、更新、テストに役立つさまざまなツールを提供します。さらに、ルーティングやフォーム管理などの多くの機能も提供します。このガイドでは、Ubuntu24 に Angular をインストールする方法について説明します。まず、Node.js をインストールする必要があります。 Node.js は、ChromeV8 エンジンに基づく JavaScript 実行環境で、サーバー側で JavaScript コードを実行できます。ウブにいるために

Angularでモナコエディタを使用するにはどうすればよいですか?以下の記事は、最近業務で使用したangularでのmonaco-editorの使い方を記録したものですので、皆様のお役に立てれば幸いです。

Angular Universal をご存知ですか?これは、Web サイトがより優れた SEO サポートを提供するのに役立ちます。

この記事では、Angular の実践的な経験を共有し、angualr と ng-zorro を組み合わせてバックエンド システムを迅速に開発する方法を学びます。

インターネットの急速な発展に伴い、フロントエンド開発テクノロジーも常に改善され、反復されています。 PHP と Angular は、フロントエンド開発で広く使用されている 2 つのテクノロジーです。 PHP は、フォームの処理、動的ページの生成、アクセス許可の管理などのタスクを処理できるサーバー側スクリプト言語です。 Angular は、単一ページ アプリケーションの開発やコンポーネント化された Web アプリケーションの構築に使用できる JavaScript フレームワークです。この記事では、PHPとAngularをフロントエンド開発に使用する方法と、それらを組み合わせる方法を紹介します。

この記事では、Angular のステートマネージャー NgRx について深く理解し、NgRx の使用方法を紹介します。

認証は、Web アプリケーションの最も重要な部分の 1 つです。このチュートリアルでは、トークンベースの認証システムと、それが従来のログイン システムとどのように異なるかについて説明します。このチュートリアルを終えると、Angular と Node.js で書かれた完全に動作するデモが表示されます。従来の認証システム トークンベースの認証システムに進む前に、従来の認証システムを見てみましょう。ユーザーはログイン フォームにユーザー名とパスワードを入力し、[ログイン] をクリックします。リクエストを行った後、データベースにクエリを実行してバックエンドでユーザーを認証します。リクエストが有効な場合、データベースから取得したユーザー情報を使用してセッションが作成され、セッション情報が応答ヘッダーで返され、セッション ID がブラウザに保存されます。対象となるアプリケーションへのアクセスを提供します。
