The HtmlTargetElement attribute controls which elements a tag helper transforms. Its first argument selects the element name; named properties narrow the match by attributes, parent element, or tag structure. section 25.2.4
Use the selector deliberately:
- Set Attributes to a comma-separated list such as "bg-color,text-color"; CSS attribute selectors support presence, exact-value, prefix, and wildcard-prefix matching. section 25.2.4
- Set ParentTag to require a containing element, such as matching only tr elements inside thead. section 25.2.4
- Set TagStructure to constrain normal, self-closing, or without-end-tag structures. section 25.2.4
- Use "*" to match any element, but prefer multiple narrowly targeted attributes when broad matching could transform unintended elements. section 25.2.5
Targeting table headers
A tag helper can target only header rows carrying both styling attributes: [HtmlTargetElement("tr", Attributes = "bg-color,text-color", ParentTag = "thead")]. A request rendering /home/index/1 then transforms the matching tr while leaving other rows alone. section 25.2.4
Listing 25.8 Narrowing scope in the TrTagHelper.cs file in the TagHelpers folder
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace WebApp.TagHelpers {
[HtmlTargetElement("tr", Attributes = "bg-color,text-color",
ParentTag = "thead")]
public class TrTagHelper : TagHelper {
public string BgColor { get; set; } = "dark";
public string TextColor { get; set; } = "white";
public override void Process(TagHelperContext context,
TagHelperOutput output) {
output.Attributes.SetAttribute("class",
$"bg-{BgColor} text-center text-{TextColor}");
}
}
}
Inspect the complete TrTagHelper implementation and its matching criteria. section 25.2.4
Applying the attribute more than once supports a controlled union of targets, such as tr elements with two attributes and td elements with bg-color. It is also required when targeting a custom element such as tablehead; class-name convention applies only to standard element names. section 25.2.5 section 25.3.1
For tag helper components, HtmlTargetElement can expand processing beyond head and body to elements such as table. Every registered component then receives the selected elements, so broad selectors affect all components. section 25.4.2
