>  기사  >  웹 프론트엔드  >  각도를 사용하여 메시지 구성 요소 작성 완료

각도를 사용하여 메시지 구성 요소 작성 완료

亚连
亚连원래의
2018-06-20 15:19:421659검색

이 글에서는 주로 Message 컴포넌트의 Angle 버전을 작성하는 방법을 소개합니다. 편집자는 꽤 좋다고 생각하므로 지금 공유하고 참고용으로 제공하겠습니다. 에디터를 따라가서 살펴보세요

프레임워크나 라이브러리를 배우는 가장 좋은 방법은 공식 문서를 읽고 예제 작성을 시작하는 것입니다. 최근 시간이 날 때마다 Angular를 배워서 오늘은 메시지 컴포넌트를 작성하고 메시지 서비스를 통해 메시지 컴포넌트를 동적으로 로드해 보겠습니다.
내가 참여하는 프로젝트는 기본적으로 jquery로 완성됩니다. 이전에는 아래와 같이 프로젝트에 간단한 메시지 플러그인을 직접 작성했습니다.

이제 각도(버전 5.0.0)를 사용하여 메시지 구성 요소를 구현합니다.

메시지 구성요소

메시지 구성요소는 수신 유형, 메시지 및 기간에 따라 표시되어야 합니다. message.comComponent.ts, message.comComponent.html, message.comComponent.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-->
<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. 공급자 제공

  2. 인젝터 인스턴스 만들기

  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

For 만들기 코드 재사용, 여기에 일반 로더 클래스를 생성하세요 구성 요소의 동적 생성을 완료합니다. 그중 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);
  }
}

message service

message 서비스는 메시지 표시를 위한 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{
}

Usage method

MessageService를 삽입하고 API를 호출하여 메시지 구성 요소를 사용합니다.

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

위 내용은 모두를 위해 제가 정리한 내용입니다. 앞으로 모든 사람에게 도움이 되기를 바랍니다.

관련 기사:

Vue 구성 요소 Toast에서 표시 상자 효과를 구현하는 방법

webpack의 규칙 매개변수 처리 정보

AngularJS에서 간단한 계산을 구현하는 방법

위 내용은 각도를 사용하여 메시지 구성 요소 작성 완료의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.