【发布时间】:2019-12-06 16:01:56
【问题描述】:
我有一个显示或隐藏 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();
});
}
}
正如预期的那样,当result 为true 时,这会将DIV 添加到页面中。
但是当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
我该怎么做?
【问题讨论】:
-
this.viewContainer.clear()? -
在我看来,您最好的选择是在指令中保持状态,然后将订阅的值与您的状态进行比较。
标签: angular typescript rxjs angular8