2017-01-22 19 views
14

我想實現與angular-permisssion類似的操作。並要求控制元素的存在,我需要使用角structural directive如何使用帶有多個輸入的角度結構指令

在開始的時候,我覺得這樣的語法將工作:

<h2 *permissionIf [permissionIfExcept]="'Read'">Except</h2> 

但是,它不工作的方式。

此外,官方指南只教你如何編寫自定義結構指令與單一輸入。有了多輸入,一些第三方教程會涉及一些。但是,這是使用角模板微語法來實現數據綁定。然後出現一個問題: 模板語法不支持純鍵值輸入:

<h2 *permissionIf="except: map.except;only: 'test'">Except</h2> 

它擴展到該(這是違法的):

<h2 template="permissionIf except: map.except;only: 'test'">Except</h2> 

甲笨臨時解決方案是增加一個無用變量聲明。

<h2 *permissionIf="let i;except: map.except;only: 'test'">Except</h2> 

另一個不方便的方法是使用template元素來包裝代碼。

<template permissionIf [permissionIfExcept]="'Read'"> 
    <h2>Except</h2> 
</template> 

以上所有內容都不夠完善。但我找不到解決它的方法。

希望有些人可以給一些建議:)。

回答

13

輸入名稱需要所有與該指令的選擇前綴:

@Directive({ 
    selector: '[permissionIf]' 
    }) 
    export class PermissionIfDirective implements AfterContentInit { 

    private _permissionIf:string[]; 
    @Input() 
    set permissionIf(value: string[]) { 
     this._permissionIf=value; 
     console.log('permissionIf: ', value); 
    } 

    private _except:string; 
    @Input() 
    set permissionIfExcept(value: string) { 
     this._except = value; 
     console.log('except: ', value); 
    } 
    } 

,並使用它像

<div *permissionIf="permissions;except:'Read'"></div> 

請不:的分配。

的明確的形式看起來像

<template [permissionIf]="permissions" [permissionIfExcept]="'Read'"> 
    </div></div> 
</template> 

<ng-container>它可能看起來像

<ng-container *permissionIf="permissions;except:'Read'"> 
    <div></div> 
</ng-container> 

Plunker example

另見的NgFor源爲例https://github.com/angular/angular/blob/d4d3782d455a484e8aa26ec9a57ee2b4727bc1da/modules/%40angular/common/src/directives/ng_for.ts

+0

你解答是類似的o我的第一個解決方案意味着'權限'是無用的。 –

+0

對不起,我不明白你的意思是無用的。我試圖演示如何將值傳遞給多個輸入。我沒有看到多個解決方案。只有這一種方式。 –

+0

「無用」是指標識符用於避免語法錯誤,並沒有實際的用法。 –