gpt4 book ai didi

angular - 指令中的主机属性是什么以及如何知道这些细节

转载 作者:行者123 更新时间:2023-12-03 23:35:33 25 4
gpt4 key购买 nike

嗨,我使用 angular 8 和 ng-bootstrap 在我的项目中添加表
我发现这段代码我不太明白

  @Directive({
selector: 'th[sortable]',
host: {
'[class.asc]': 'direction === "asc"',
'[class.desc]': 'direction === "desc"',
'(click)': 'rotate()'
}
})

谁能告诉我代码说什么?
以及选择器中的“th”是什么意思。
还主机我可以将其更改为其他内容,因为编辑说的是,它是旧属性还是什么
谢谢大家

最佳答案

根据 Angular documentation :

选择器

selector: The CSS selector that identifies this directive in a template and triggers instantiation of the directive.



所以在你的代码中 selector: 'th[sortable]'选择器通过 th 声明选择带有 [sortable] 的元素名称属性。你应该找到类似 <th sortable>... 的东西在你的 html 文件中。

更新以回答评论:
根据 link在评论中分享,这里是 th sortable在 html 代码中:
enter image description here

主持人

host: Maps class properties to host element bindings for properties, attributes, and events, using a set of key-value pairs.



host: {
[key: string]: string;
}

最好使用 @HostBinding@HostListener而不是 host通过 Angular 风格指南,检查 this link更多细节。

替换 host在您的代码中:
@HostBinding允许您在承载指令的元素或组件上设置属性。所以它将取代您的 [class.asc][class.desc]代码如下 在您的指令中 :

@HostBinding('class.asc') direction = 'asc';

@HostBinding('class.desc') direction = 'desc';
@HostListener允许您监听宿主元素或组件上的事件。所以你的 '(click)'代码将替换为以下 在您的指令中 :

@HostListener('click') rotate() { 
// todo:
}

关于angular - 指令中的主机属性是什么以及如何知道这些细节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58566808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com