Html 如何生成添加类的指令;“显示”;点击链接,引导4类进入无序列表(不可见)?
我被分配了一个任务,我必须在单击时打开一个bootstrap 4下拉菜单,方法是发出一个指令,在单击下拉菜单时将一个show类添加到无序列表中(不允许使用bootstrap javascript cdn) 我制作了一个名为“appDropdown”的指令,它将类“show”绑定到一个名为“isOpen”的布尔变量,然后我监听一次单击,然后切换“isOpen”变量,因此每当我单击该指令所在的元素时,就会添加或删除类“show” HTML代码Html 如何生成添加类的指令;“显示”;点击链接,引导4类进入无序列表(不可见)?,html,angular,typescript,bootstrap-4,Html,Angular,Typescript,Bootstrap 4,我被分配了一个任务,我必须在单击时打开一个bootstrap 4下拉菜单,方法是发出一个指令,在单击下拉菜单时将一个show类添加到无序列表中(不允许使用bootstrap javascript cdn) 我制作了一个名为“appDropdown”的指令,它将类“show”绑定到一个名为“isOpen”的布尔变量,然后我监听一次单击,然后切换“isOpen”变量,因此每当我单击该指令所在的元素时,就会添加或删除类“show” HTML代码 <div class="col-xs-12
<div class="col-xs-12">
<div class="dropdown">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Manage Recipe <span class="caret"></span>
</button>
<ul class="dropdown-menu" appDropdown> <!--this is where i need a class 'show' to be added when the above button is clicked !-->
<li class="dropdown-item"><a href="#">Add Ingredients to Shopping Lists</a></li>
<li class="dropdown-item"><a href="#">Edit recipe</a></li>
<li class="dropdown-item"><a href="#">Delete recipe</a></li>
</ul>
</div>
</div>
</div>
本应在下拉按钮的切换上添加或删除类显示,但不会发生任何情况您可以在指令中使用
exportAs
元属性来实现您想要的:
首先,定义一个指令
import { Directive, ElementRef, Input, HostBinding, HostListener } from "@angular/core";
@Directive({
selector: "[appDropdown]",
exportAs: "myDir"
})
export class DropDownDirective {
public isShow = false;
@HostBinding("class.show") get opened() {
return this.isShow;
}
@HostListener("click") open() {
this.isShow = !this.isShow;
}
}
然后在组件中定义一个ViewChild
以访问按钮:
export class AppComponent implements AfterViewInit {
@ViewChild("temp", { static: true }) vc: DropDownDirective;
ngAfterViewInit() {
console.log(this.vc.isShow);
}
}
最后在html中:
<div class="dropdown">
<button #temp=myDir appDropdown type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Manage Recipe <span class="caret"></span>
</button>
<ul class="dropdown-menu" [class.show]="this.vc.isShow">
<li class="dropdown-item"><a href="#">Add Ingredients to Shopping Lists</a></li>
<li class="dropdown-item"><a href="#">Edit recipe</a></li>
<li class="dropdown-item"><a href="#">Delete recipe</a></li>
</ul>
</div>
管理配方
嘿,AbolfazIR,谢谢你的解决方案,但我想做一个通用指令,这样我就不必使用components typescript文件了,有什么办法可以实现吗?
<div class="dropdown">
<button #temp=myDir appDropdown type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Manage Recipe <span class="caret"></span>
</button>
<ul class="dropdown-menu" [class.show]="this.vc.isShow">
<li class="dropdown-item"><a href="#">Add Ingredients to Shopping Lists</a></li>
<li class="dropdown-item"><a href="#">Edit recipe</a></li>
<li class="dropdown-item"><a href="#">Delete recipe</a></li>
</ul>
</div>