[Angular] Implementing A General Communication Mechanism For Directive Interaction
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的更多相关文章
- Linux Communication Mechanism Summarize
目录 . Linux通信机制分类简介 . 控制机制 0x1: 竞态条件 0x2: 临界区 . Inter-Process Communication (IPC) mechanisms: 进程间通信机制 ...
- [转]A Faster UIWebView Communication Mechanism
ref:http://blog.persistent.info/2013/10/a-faster-uiwebview-communication.html Use location.hash or t ...
- angular源码分析:$compile服务——directive他妈
一.directive的注册 1.我们知道,我们可以通过类似下面的代码定义一个指令(directive). var myModule = angular.module(...); myModule.d ...
- [Angular] Implementing a ControlValueAccessor
So when you need to create a ControlValueAccessor? When you want to use a custom component as form c ...
- NetLink Communication Mechanism And Netlink Sourcecode Analysis
catalog . Netlink简介 . Netlink Function API Howto . Generic Netlink HOWTO kernel API . RFC Linux Netl ...
- Angular之指令Directive系列
项目筹备近期开启Angular学习,指令比较难理解所以记录备案,推荐Angualr实战学习视频大漠穷秋 Angular实战 一.指令directive概述 指令可以对元素绑定事件监听或者改变DOM结构 ...
- ANGULARJS: UNDERSTANDING DIRECTIVE SCOPE
https://www.3pillarglobal.com/insights/angularjs-understanding-directive-scope --------------------- ...
- Angular中Constructor 和 ngOnInit 的本质区别
在Medium看到一篇Angular的文章,深入对比了 Constructor 和 ngOnInit 的不同,受益匪浅,于是搬过来让更多的前端小伙伴看到,翻译不得当之处还请斧正. 本文出处:The e ...
- PatentTips - Compare and exchange operation using sleep-wakeup mechanism
BACKGROUND Typically, a multithreaded processor or a multi-processor system is capable of processing ...
随机推荐
- HDU 2633 Getting Driving License(模拟)
Getting Driving License Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/ ...
- Linux MTD 子系统
一.MTD子系统概述 MTD(Memory Technology Device, 内存技术设备)是用于访问memory 设备 (ROM.FLASH)的Linux子系统. 主要目的是为了使新的memor ...
- 源码安装 ipython
https://blog.csdn.net/huobanjishijian/article/details/51470898
- Springboot2.0访问Redis集群
Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作高性能的key-value数据库.缓存和消息中间件,掌握它是程序员的必备技能,下面是一个springboot访问redis的 ...
- 洛谷——P1525 关押罪犯
https://www.luogu.org/problem/show?pid=1525 题目描述 S 城现有两座监狱,一共关押着N 名罪犯,编号分别为1~N.他们之间的关系自然也极不和谐.很多罪犯之间 ...
- 洛谷 P2021 faebdc玩扑克
P2021 faebdc玩扑克 题目背景 faebdc和zky在玩一个小游戏 题目描述 zky有n个扑克牌,编号从1到n,zky把它排成一个序列,每次把最上方的扑克牌放在牌堆底,然后把下一张扑克牌拿出 ...
- Oracle与MySQL的转化差异
1.nvl函数. Oracle 中 : nvl (join_count , 0) MySQL中:if(join_count is null,'0',join_count) ...
- 求第k大的数(用到快速排序算法的思想)
//下面两种part效率比较:相同运算量下part比part2快5倍左右,part2写法简单但是效率低 #include "stdafx.h" #include <iostr ...
- 18.Node.js 事件循环
转自:http://www.runoob.com/nodejs/nodejs-tutorial.html Node.js 是单进程单线程应用程序,但是通过事件和回调支持并发,所以性能非常高. Node ...
- BZOJ4196: [Noi2015]软件包管理器(树链剖分)
Description Linux用户和OSX用户一定对软件包管理器不会陌生.通过软件包管理器,你可以通过一行命令安装某一个软件包,然后软件包管理器会帮助你从软件源下载软件包,同时自动解决所有的依赖( ...