簡體   English   中英

angular 4.根據if刪除構造函數中的組件

[英]angular 4. remove a component in the constructor based on an if

我想為組件添加保護。 如果用戶沒有權限查看此組件,則不會呈現該組件。

我已經嘗試將我的if放在構造函數中並返回false但它仍然呈現。

我還添加了if到模板本身,但當時我沒有看到看法,但該組件還活着,並增加了復雜的代碼,因為我需要保持同樣的幾個地方if

有沒有辦法告訴組件根本不渲染?

  constructor( private userService: UserService) { if (this.userService.isAllowed("see_trade_groups") === false) { return; } } 

為此,您可以看到CanActivate 把它放在組件route ,它將完成你想要的工作。

在那里你可以編寫一個邏輯,根據該邏輯導航路由。

組件編譯生命周期由Angular編譯器處理,因此組件無法控制自己的生命周期,應該從外部控制它。

處理此問題的常用方法是使用路由器。 路由組件的生命周期與常規組件不同,因為它由路由器處理; 它們連接到<router-outlet>組件。 可以防止在路由組件中進行編譯,但不能在常規組件中進行編譯

否則,應該使用指令處理。 ngIf是內置的方法,可以防止編譯常規組件。

所以它變成了

<foo *ngIf="userService.isAllowed('see_trade_groups')"></foo>

由於這需要在每次需要時將userService注入父組件,這將導致大量的樣板代碼。 一個合適的解決方案是創建一個行為與ngIf類似的指令 - 或者擴展它以提供所需的功能:

import {Input, OnChanges, SimpleChanges, TemplateRef, ViewContainerRef} from '@angular/core';
import {NgIf, NgIfContext} from '@angular/common';

...

@Directive({
    selector: '[role]'
})
class Role extends NgIf {
    @Input() role: string;

    constructor(
        viewContainer: ViewContainerRef,
        templateRef: TemplateRef<NgIfContext>
        public userService: User
    ) {
        super(viewContainer, templateRef);
    }

    ngOnChanges({ role }: SimpleChanges) {
        this.ngIf = this.userService.isAllowed(role);
        // can also subscribe to some observable to add/remove a component any time 
    }
}

使用如下:

<foo *role="'see_trade_groups'"></foo>

請注意, Role*結構指令。 這允許它控制指定元素的編譯,類似於ngIfngFor

暫無
暫無

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

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