Angular指令问题:点击表头无法显示排序上下图标
It looks like your sorting logic is set up correctly (the SortableHeaderDirective emits the sort event, and you're handling it in onSort), but the missing icons are almost certainly a CSS issue—either you don't have styles defined for the .asc/.desc classes, or the styles aren't being applied properly.
Let's break down the fixes step by step:
1. Add CSS for Sort Icons
The original project you referenced uses CSS to display up/down arrows when the .asc or .desc class is added to the <th> element. You'll need to add similar styles to your project.
Here's a self-contained example that works with your existing .thead-light class (no external icon libraries required):
/* Make sortable headers look interactive */ thead.thead-light th[sortable] { cursor: pointer; user-select: none; position: relative; padding-right: 24px; /* Reserve space for the icon */ } /* Create arrow icons using pseudo-elements */ thead.thead-light th[sortable].asc::after, thead.thead-light th[sortable].desc::after { content: ''; position: absolute; right: 8px; top: 50%; transform: translateY(-50%); border-left: 4px solid transparent; border-right: 4px solid transparent; } thead.thead-light th[sortable].asc::after { border-bottom: 4px solid #495057; /* Match Bootstrap's thead-light text color */ } thead.thead-light th[sortable].desc::after { border-top: 4px solid #495057; }
This adds small arrow icons to the right of each sortable header when the corresponding class is applied.
2. Verify the Directive is Working Correctly
Before diving deeper into styles, confirm the directive is actually adding the .asc/.desc classes to your <th> element:
- Open your browser's DevTools (F12) and navigate to the Elements tab.
- Click on a sortable header.
- Check if the
<th>element now has anascordescclass applied.
If the classes aren't showing up:
- Make sure you've declared
SortableHeaderDirectivein your Angular module'sdeclarationsarray. - Double-check that your
<th>has thesortableattribute set correctly (yoursortable="{{ item.content }}"should work as long asitem.contentis a non-empty string).
3. Resolve Style Conflicts
If the classes are applied but icons still don't appear:
- Use DevTools' Styles tab to inspect the
::afterpseudo-element—look for crossed-out properties that indicate conflicting CSS (like Bootstrap defaults overriding your styles). - Increase the specificity of your selectors (the example above uses
thead.thead-light th[sortable].asc::after, which is more specific than a simple.asc::after). - Ensure there's no
overflow: hiddenon the<th>element, which would hide the pseudo-element icon.
Once you add the correct CSS and confirm the classes are being applied, the sort icons should appear when you click the headers!
内容的提问来源于stack exchange,提问作者Gly

