首页 > 解决方案 > 在指令中从页面中添加/删除 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 resultis true

但是当authorize方法更新并返回一个新的value并且result是再次添加时。trueDIV

当返回的值authorize更新时,我想:

if (value == false)
  // Remove DIV if exists in page
if (value == true)
  // Add DIV if does not exist in page

我怎样才能做到这一点?

标签: angulartypescriptrxjsangular8

解决方案


您想使用distinctUntilChanged()以便 observable 不会发出重复值。

    this.authorizationService.authorize(this.id).pipe(
       distinctUntilChanged()
    ).subscribe(result => {
      if (result == true)
        this.viewContainer.createEmbeddedView(this.templateRef)
      else 
        this.viewContainer.clear();
    });

推荐阅读