[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 ...
随机推荐
- [Python's] Python's list comprehensions a
# Python's list comprehensions are awesome. vals = [expression for value in collection if condition] ...
- [Angular] Make a chatbot with DialogFlow
Register a account on https://console.dialogflow.com/api-client/ "Creat a intent" -- you c ...
- VBA调试利器debug.print
作者:iamlaosong 百度一下.非常easy找到debug.print解释和使用介绍.事实上非常简单.就是将代码运行结果显示在"马上窗体"中,但不影响程序运行.VBA程序调试 ...
- [BZOJ1672][Usaco2005 Dec]Cleaning Shifts 清理牛棚 线段树优化DP
链接 题意:给你一些区间,每个区间都有一个花费,求覆盖区间 \([S,T]\) 的最小花费 题解 先将区间排序 设 \(f[i]\) 表示决策到第 \(i\) 个区间,覆盖满 \(S\dots R[i ...
- Flume的可扩展性
Flume的可扩展性:Flume采用了三层架构,分别为agent,collector和storage,每一层均可以水平扩展.其中,所有agent和 collector由master统一管理,这使得系统 ...
- SGU 253 Theodore Roosevelt 快速判断点是否在凸包内
http://acm.sgu.ru/problem.php?contest=0&problem=253 题意简单易懂...给你n个点的凸包(经测试已经是极角序)...判断m个点是否在凸包内.. ...
- 二、Docker基础操作
原文:二.Docker基础操作 一.下载镜像 命令:docker pull xxxxxx(镜像名) docker pull training/weapp 二.运行镜像 docker run -d -P ...
- 【习题 7-7 UVA-12558】Egyptian Fractions (HARD version)
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 迭代加深搜索. 枚举最大量maxdep 在dfs里面传剩余的要凑的分子.分母 以及上一次枚举的值是多少. 然后找到最小的k,满足1/ ...
- 【Good Bye 2017 C】 New Year and Curling
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 枚举前i-1个圆. 哪些圆和它相交. 取圆心纵坐标最大的那个圆就可以了. [代码] #include <bits/stdc++ ...
- 【Educational Codeforces Round 35 B】Two Cakes
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 从小到大枚举x. 看看a/x+b/x是不是大于等于n 是的话. 看看是不是两种蛋糕都能凑一堆. 也即x的最大枚举量是min(a,b) ...