我得到了一个任务,我必须在单击时打开一个引导程序 4 下拉菜单,通过发出一个指令,该指令将在单击下拉列表时将 show 类添加到无序列表中(不允许引导 JavaScript CDN(
我制作了一个名为"appDropdown"的指令,它将类"show"绑定到一个名为"isOpen"的布尔变量,然后我监听单击,然后切换"isOpen"变量,因此每当我单击类"show"都会在放置指令的元素处添加或删除。
网页代码
<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>
角度代码
import {Directive, HostListener, HostBinding,OnInit} from '@angular/core';
@Directive({
selector:'[appDropdown]'
})
export class appDropdown implements {
@HostBinding('class.show') isOpen:boolean=false;
@HostListener('click',['$event.target']) toggleOpen(target){
this.isOpen=!this.isOpen;
console.log(this.isOpen);
console.log(target)
}
预计在下拉按钮的切换时添加或删除类节目,但没有任何反应
你可以在指令中使用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>
堆叠闪电战在这里