【发布时间】:2020-03-15 05:26:23
【问题描述】:
我正在使用 angular 4,并且我有一个指令,我需要在我的模板上添加它来验证一些东西。但我想先评估另一个条件是否为真,然后应用该指令。现在我的代码是这样的:
<div *ngIf="groupCheck; else NoDirective" #Directive>
<li [directive]="controlGroup"><a [routerLink]="['/account/search/', '']"
routerLinkActive="active">Accounts</a></li>
<li [directive]="controlGroup"><a [routerLink]="['/orders', '']"
routerLinkActive="active">Orders</a></li>
<li [directive]="DIFFERENT_GROUP"><a [routerLink]="['/report']" routerLinkActive="active">Reports</a>
</li>
<li [directive]="controlGroup"><a [routerLink]="['/anotherStuff']" routerLinkActive="active">anotherStuff</a></li>
</div>
<div *ngIf="!groupCheck; else Directive" #NoDirective>
<li><a [routerLink]="['/account/search/', '']" routerLinkActive="active">Accounts</a></li>
<li><a [routerLink]="['/orders', '']" routerLinkActive="active">Orders</a></li>
<li><a [routerLink]="['/report']" routerLinkActive="active">Reports</a></li>
<li><a [routerLink]="['/anotherStuff']" routerLinkActive="active">anotherStuff</a></li>
</div>
我想找到一种方法来做这样的事情:
<li *NgIf="condition true add [directive]=controlGroup; else Don't add directive to this line/tag/element"><a [routerLink]="['/account/search/', '']"
routerLinkActive="active">Accounts</a></li>
<li *NgIf="condition true add [directive]=controlGroup; else Don't add directive to this line/tag/element"><a [routerLink]="['/orders', '']"
routerLinkActive="active">Orders</a></li>
<li *NgIf="condition true add [directive]=DIFFERENTGROUP; else Don't add directive to this line/tag/element"><a [routerLink]="['/report']" routerLinkActive="active">Reports</a>
</li>
<li *NgIf="condition true add [directive]=controlGroup; else Don't add directive to this line/tag/element"><a [routerLink]="['/anotherStuff']" routerLinkActive="active">anotherStuff</a></li>
这样我就不必只为一个条件重写整个代码,也不需要条件 div。有没有办法做到这一点?
--******更新******-- @Allabakash 从帖子中为我提供了一个可能的解决方案:
<button [attr.md-raised-button]="condition ? '' : null"></button>
我现在的问题是,如果我的指令(我无法访问)为 null 或方法中没有出现的名称,它会消除整个元素。以下是它的工作原理:
set checkGroup(hasGroups: string) {
if (hasGroups) {
this.AuthService.hasOtherGroups(hasGroups, false).subscribe(res => {
if (!res) {
this.el.nativeElement.parentNode.removeChild(this.el.nativeElement);
} else {
this.el.nativeElement.style.display = '';
}
});
} else {
this.el.nativeElement.parentNode.removeChild(this.el.nativeElement);
}
}
这给我留下了大问题:有没有办法可以在
中使用这个指令和条件感谢您的宝贵时间 :)。
【问题讨论】:
-
我在找什么,谢谢。问题是我需要使用的该死指令。如果我传递一个空值,它会删除整个元素。这就是指令的工作方式,我无法更改它。我将用指令的工作原理更新问题。
标签: angular typescript directive angular-ng-if