angular - 在指令中从页面中添加/删除 HTML 元素
问题描述
我有一个显示或隐藏 HTML 元素 [StackBlitz][1] 的指令:
<div *authorize="12">{{user.name}}</div>
授权指令是:
export class AuthorizeDirective implements OnInit {
id: number;
@Input() set authorize(id: number) {
this.id = id;
}
constructor(private authService: AuthService, private element: ElementRef, private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) { }
ngOnInit() {
this.authorizationService.authorize(this.id).subscribe(result => {
if (result == true)
this.viewContainer.createEmbeddedView(this.templateRef)
else
this.viewContainer.clear();
});
}
}
正如预期的那样,这将 添加DIV
到页面 when result
is true
。
但是当authorize
方法更新并返回一个新的value
并且result
是再次添加时。true
DIV
当返回的值authorize
更新时,我想:
if (value == false)
// Remove DIV if exists in page
if (value == true)
// Add DIV if does not exist in page
我怎样才能做到这一点?
解决方案
您想使用distinctUntilChanged()以便 observable 不会发出重复值。
this.authorizationService.authorize(this.id).pipe(
distinctUntilChanged()
).subscribe(result => {
if (result == true)
this.viewContainer.createEmbeddedView(this.templateRef)
else
this.viewContainer.clear();
});
推荐阅读
- c++ - 用于 localhost:Port 的 MSVC++ 中的 TLS 客户端
- powershell - 如何将其值中包含连字符的$变量作为参数传递给另一个函数
- javascript - 如何通过将鼠标悬停在 sigmaJs 中的当前节点上仅对当前节点和连接节点绘制标签为真?
- razor - DB2 razor 中的列或参数定义无效
- javascript - triggerHandler 'rightnow' 没有在页面刷新时更新
- wijmo - Wijmo Flexgrid 如何获取粘贴的行数/获取粘贴数据的行的索引
- javascript - 如何检索当前远程脚本的 URL?
- python - 更新数据集成逻辑
- r - 在数字数据的字符串中嵌入 nul
- google-app-maker - Google 应用制作工具中的驱动器选择器停止工作