[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 ...
随机推荐
- Day1上午解题报告
预计分数:100+60+0=160 实际分数:100+30+20=150 T1立方数(cubic) 题目描述 LYK定义了一个数叫“立方数”,若一个数可以被写作是一个正整数的3次方,则这个数就是立方数 ...
- Nabou应用实例
本文接上文 <完整性检查工具Nabou> http://chenguang.blog.51cto.com/350944/280712650) this.width=650;" ...
- IFC数据模式架构的四个概念层
IFC模型体系结构由四个层次构成, 从下到上依次是 资源层(Resource Layer).核心层(Core Layer).交互层(Interoperability Layer).领域层(Domain ...
- MyBatis学习总结(11)——MyBatis动态Sql语句
MyBatis中对数据库的操作,有时要带一些条件,因此动态SQL语句非常有必要,下面就主要来讲讲几个常用的动态SQL语句的语法 MyBatis中用于实现动态SQL的元素主要有: if choose(w ...
- 杭电(hdu)2053 Switch Game 水题
Switch Game Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Tota ...
- wordpress 加速主题的静态资源
wordpress 加速主题的静态资源(固定的CSS.JS和图片等) wordpress 中用函数 get_stylesheet_directory_uri() 生成当前主题的 URL , 格式如 h ...
- centos7 Another app is currently holding the yum lock; waiting for it to exit...
解决方法:rm -rf /var/run/yum.pid 来强行解除锁定,然后你的yum就可以运行了
- JAVA MessageDigest(MD5加密等)
转自http://blog.csdn.net/hudashi/article/details/8394158 一.概述 java.security.MessageDigest类用于为应用程序提供信息摘 ...
- NOIP2015运输计划(二分答案)
题目描述 公元2044年,人类进入了宇宙纪元. L国有n个星球,还有n-1条双向航道,每条航道建立在两个星球之间,这n-1条航道连通了L国的所有星球. 小P掌管一家物流公司,该公司有很多个运输计划,每 ...
- 内核中的宏定义__init、__initdata和__exit、__exitdata
__init.__initdata和__exit.__exitdata的定义位于<kernel/include/linux/init.h> /* These are for everybo ...