用作 ng-if (Angular 2) 的指令
Directive that works as ng-if (Angular 2)
我正在尝试创建一个用作 ngIf 的指令来控制是否允许具有正确权限的用户查看特定内容,如下所示:
<div [type-of-user]="load data from the user and check it (normal or premium)">
<h3>You are allow to see this.</h3>
</div>
我正在阅读有关如何执行此操作的信息,并在 doc 上找到了关于 "Attribute Directives" 的内容,但我仍然无法实现它(我是 Angular 2 的新手)
到目前为止我有这个:
import {Directive, ElementRef, Input} from '@angular/core';
@Directive({
selector: '[type-of-user]'
})
export class TypeOfUserDirective{
constructor(private el: ElementRef){}
@Input('type-of-user') userControl: string;
private haspermission(permission: string) {
/*the style background color is just to test if works*/
this.el.nativeElement.style.backgroundColor = permission;
}
}
我已经在 app.module 中添加了指令。
任何关于如何进行的建议都会很棒。
经过更多研究后,我找到了一个很棒的文档,介绍如何构建自定义指令,特别是我需要的方式,它充当 ngIf 指令。你可以阅读它 here and see the plunkr here
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[isAllow]'
})
export class isAllowDirective {
constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}
@Input() set isAllow(allow: boolean){
if (allow) {
// If condition is true add template to DOM
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
// Else remove template from DOM
this.viewContainer.clear();
}
}
}
已接受的答案未使用 angular 的 *ngIf
实现。
我编写了一个使用它的自定义 *ngIf
指令:
http://avenshteinohad.blogspot.com/2018/06/custom-ngif-directive.html
我正在尝试创建一个用作 ngIf 的指令来控制是否允许具有正确权限的用户查看特定内容,如下所示:
<div [type-of-user]="load data from the user and check it (normal or premium)">
<h3>You are allow to see this.</h3>
</div>
我正在阅读有关如何执行此操作的信息,并在 doc 上找到了关于 "Attribute Directives" 的内容,但我仍然无法实现它(我是 Angular 2 的新手)
到目前为止我有这个:
import {Directive, ElementRef, Input} from '@angular/core';
@Directive({
selector: '[type-of-user]'
})
export class TypeOfUserDirective{
constructor(private el: ElementRef){}
@Input('type-of-user') userControl: string;
private haspermission(permission: string) {
/*the style background color is just to test if works*/
this.el.nativeElement.style.backgroundColor = permission;
}
}
我已经在 app.module 中添加了指令。
任何关于如何进行的建议都会很棒。
经过更多研究后,我找到了一个很棒的文档,介绍如何构建自定义指令,特别是我需要的方式,它充当 ngIf 指令。你可以阅读它 here and see the plunkr here
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[isAllow]'
})
export class isAllowDirective {
constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}
@Input() set isAllow(allow: boolean){
if (allow) {
// If condition is true add template to DOM
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
// Else remove template from DOM
this.viewContainer.clear();
}
}
}
已接受的答案未使用 angular 的 *ngIf
实现。
我编写了一个使用它的自定义 *ngIf
指令:
http://avenshteinohad.blogspot.com/2018/06/custom-ngif-directive.html