簡體   English   中英

為什么 Angular 2+ 結構指令不更新視圖?

[英]Why Angular 2+ structural directive doesn't update the view?

在我的應用程序中,我有一個具有權限數組的帳戶服務,因此我創建了一個結構指令來決定是否顯示操作的按鈕,但問題是當我登錄/注銷並更新權限數組時,該指令沒有t 更新視圖。

這是代碼:

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { Account } from './models';
import { AccountService } from './account.service';

@Directive({
  selector: '[appAuth]',
})
export class AuthDirective {

  @Input() set appAuth(action: string) {
    if (this._account.permissions.includes(action)) {
      this._contRef.createEmbeddedView(this._tmplRef);
    } else {
      this._contRef.clear();
    }
  }

  constructor(
    private _contRef: ViewContainerRef,
    private _tmplRef: TemplateRef<any>,
    private _account: AccountService
  ) { }

}

以下是該指令的使用示例:

<button
  class="btn btn-default"
  *appAuth="'find-accounts'"
  (click)="doSomething()">
  Find Accounts
</button>
import { Account, AccountService } from '../common';
import { Subscription } from 'rxjs/Subscription';
import {
  Directive, Input, TemplateRef, ViewContainerRef, OnInit, OnDestroy
} from '@angular/core';

@Directive({
  selector: '[appAuth]',
})
export class AuthDirective implements OnInit, OnDestroy {

  private _accountChangesSubscription: Subscription;

  @Input('appAuth') private appAuth: string;

  constructor(
    private _contRef: ViewContainerRef,
    private _tmplRef: TemplateRef<any>,
    private _account: AccountService
  ) { }

  ngOnInit() {
    this._accountChangesSubscription = this._account.changes$
      .subscribe((account: Account) => {
        const permissions = this._account.permissions;

        if (permissions && permissions.includes(this.appAuth)) {
          this._contRef.createEmbeddedView(this._tmplRef);
        } else {
          this._contRef.clear();
        }
      });
  }

  ngOnDestroy() {
    this._accountChangesSubscription.unsubscribe();
  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM