We have modal implement and now we want to implement close functionality.

Becuase we use a structure directive to do open modal on click functionality. So as you can see, the directive and modal component is spreated. We need to have some way to communcation between directive and component.

  <ng-template [auModalOpenOnClick]="[loginButton, signUpButton]">
<au-modal class="auth-modal" [body]="newModelBody">
<!-- modal body -->
</au-modal>
</ng-template>

One general communction mechanism is though serivce.

So we need to create a service which only for AuModal component:

import {NgModule, ModuleWithProviders} from '@angular/core';
import {AuModalComponent} from './au-modal.component';
import {CommonModule} from '@angular/common';
import { AuModalOpenOnClickDirective } from './au-modal-open-on-click.directive';
import {AuModalService} from 'app/au-modal/au-modal.service'; @NgModule({
declarations: [AuModalComponent, AuModalOpenOnClickDirective],
imports: [
CommonModule
],
exports: [
AuModalComponent,
AuModalOpenOnClickDirective
]
})
export class AuModalModule { /*
* Inject AuModuleService here instead of global providers is for lazy loading
* to prevent duplicate serivce name.
* */
static forRoot(): ModuleWithProviders {
return {
ngModule: AuModalModule,
providers: [
AuModalService
]
}
}
}

Because we don't want it to be global, it might affect lazy loading, have naming conflicts with other third party libs. Therefore we use 'forRoot' static method on the AuModalModule. This approach is good for lazy loading.

Service:

Service is Observable based implementation. It mean we gonna have one public method call 'close' and an public observable variable call 'close$'.

Once close() method was called, 'close$' can get notifiied.

import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject'; @Injectable()
export class AuModalService { private subject = new Subject();
close$: Observable<any> = this.subject.asObservable();
constructor() { } close() {
this.subject.next();
} }

AuModal component: We want user click outside modal body to close the modal, so we bind 'closeModal' function tot he overlay wrapper. And also we don't want user click modal body itself to trigger the close event also. So we have second method called 'cancelCloseModal' to stop event propagation.

<div class="modal-overlay" (click)="closeModal()">

  <div class="modal-body" (click)="cancelCloseModal($event)">

    <ng-container *ngIf="body; else projectionBody">
<ng-container *ngTemplateOutlet="body"></ng-container>
</ng-container> <ng-template #projectionBody>
<ng-content></ng-content>
</ng-template> </div> </div>
  closeModal() {
this.auModelService.close();
} cancelCloseModal(evt: KeyboardEvent) {
evt.preventDefault();
evt.stopPropagation();
}

Now the only thing leave to do is subscribe the 'close$' observable inside the directive, once event was triggered, we clear the component.

Directive:

import {Directive, Input, OnInit, TemplateRef, ViewContainerRef} from '@angular/core';
import {AuModalService} from './au-modal.service'; @Directive({
selector: '[auModalOpenOnClick]'
})
export class AuModalOpenOnClickDirective implements OnInit{
ngOnInit(): void {
this.auModalService.close$
.subscribe(() => this.viewContainer.clear());
} @Input()
set auModalOpenOnClick (els) { let elements: HTMLBaseElement[]; if(Array.isArray(els)) {
elements = els;
} else {
elements = [els];
} elements.forEach(el => {
el.addEventListener('click', () => {
this.viewContainer.clear();
this.viewContainer.createEmbeddedView(this.template);
});
});
} constructor(
private template: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private auModalService: AuModalService
) { } }

[Angular] Implementing A General Communication Mechanism For Directive Interaction的更多相关文章

  1. Linux Communication Mechanism Summarize

    目录 . Linux通信机制分类简介 . 控制机制 0x1: 竞态条件 0x2: 临界区 . Inter-Process Communication (IPC) mechanisms: 进程间通信机制 ...

  2. [转]A Faster UIWebView Communication Mechanism

    ref:http://blog.persistent.info/2013/10/a-faster-uiwebview-communication.html Use location.hash or t ...

  3. angular源码分析:$compile服务——directive他妈

    一.directive的注册 1.我们知道,我们可以通过类似下面的代码定义一个指令(directive). var myModule = angular.module(...); myModule.d ...

  4. [Angular] Implementing a ControlValueAccessor

    So when you need to create a ControlValueAccessor? When you want to use a custom component as form c ...

  5. NetLink Communication Mechanism And Netlink Sourcecode Analysis

    catalog . Netlink简介 . Netlink Function API Howto . Generic Netlink HOWTO kernel API . RFC Linux Netl ...

  6. Angular之指令Directive系列

    项目筹备近期开启Angular学习,指令比较难理解所以记录备案,推荐Angualr实战学习视频大漠穷秋 Angular实战 一.指令directive概述 指令可以对元素绑定事件监听或者改变DOM结构 ...

  7. ANGULARJS: UNDERSTANDING DIRECTIVE SCOPE

    https://www.3pillarglobal.com/insights/angularjs-understanding-directive-scope --------------------- ...

  8. Angular中Constructor 和 ngOnInit 的本质区别

    在Medium看到一篇Angular的文章,深入对比了 Constructor 和 ngOnInit 的不同,受益匪浅,于是搬过来让更多的前端小伙伴看到,翻译不得当之处还请斧正. 本文出处:The e ...

  9. PatentTips - Compare and exchange operation using sleep-wakeup mechanism

    BACKGROUND Typically, a multithreaded processor or a multi-processor system is capable of processing ...

随机推荐

  1. 【DRF分页】

    目录 第一种 PageNumberPagination 查第n页,每页显示n条数据 第二种 LimitOffsetPagination 在第n个位置,向后查n条数据 第三种 CursorPaginat ...

  2. spark internal - 作业调度

    作者:刘旭晖 Raymond 转载请注明出处 Email:colorant at 163.com BLOG:http://blog.csdn.net/colorant/ 在Spark中作业调度的相关类 ...

  3. hdu1874 畅通project续 最短路 floyd或dijkstra或spfa

    Problem Description 某省自从实行了非常多年的畅通project计划后.最终修建了非常多路.只是路多了也不好,每次要从一个城镇到还有一个城镇时,都有很多种道路方案能够选择.而某些方案 ...

  4. Python笔记---错误笔记

    Python---错误笔记 1. Python编码问题: 我们在编写 Python 脚本时,往往会写上中文凝视. 可是有时候,当我们执行程序时.却发现例如以下错误:SyntaxError: Non-A ...

  5. lubuntu自动登录(lxde)

    lubuntu自动登录(lxde) 1.重启ubuntu,在grub界面长按shirft进入grub菜单: 2.选择recovery mode,按"e"键进入编辑页面: 3.把ro ...

  6. softInputMode- 软件盘监听事件

    软件盘的监听事件,如下 private final OnKeyListener mSubjectKeyListener = new OnKeyListener() { @Override public ...

  7. 洛谷P2660 zzc 种田

    题目背景 可能以后 zzc就去种田了. 题目描述 田地是一个巨大的矩形,然而zzc 每次只能种一个正方形,而每种一个正方形时zzc所花的体力值是正方形的周长,种过的田不可以再种,zzc很懒还要节约体力 ...

  8. Android 用Socket实现PC和手机的文件传输

    PC服务器端代码: /* * PC与<a href="http://lib.csdn.net/base/android" class='replace_word' title ...

  9. js中event事件处理

    1. HTML事件  直接添加到HTML结构中 function show() { alert('hello'); } <body> <button id="btn&quo ...

  10. C#之使用app.config可记录数据,下次打开可读取记录的数据

    一.背景 如下图所示,我通过open..按键打开了某个文件,之后我再把app给关闭掉,当再次打开app的时候,在textBox.Text上显示上一次打开的文件路径.通过使用app.config可以保存 ...