syncfusion-angular-mention
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseImplementing Syncfusion Angular Mention Component
实现Syncfusion Angular Mention组件
Component Overview & Architecture
组件概述与架构
The Mention component renders an autocomplete suggestion popup when the user types a trigger character (default ) inside a target element (a , , or similar). It is designed for:
@div[contenteditable]textarea- User tagging — tag people, teams, or resources using
@ - Hashtag suggestions — use any custom character (,
#, etc.) as the trigger/ - Rich text integration — works with divs and editors
contenteditable - Data binding — supports local arrays (strings, objects, complex objects) and remote DataManager sources
- Filtering — ,
Contains,StartsWithwith configurable min-length, debounce, and spacingEndsWith - Template customization — item, display, no-records, spinner, and group templates
- Disabled items — mark individual list items as non-selectable
- Accessibility — WCAG 2.2 compliant with full keyboard navigation and ARIA attributes
当用户在目标元素(、或类似元素)中输入触发字符(默认为)时,Mention组件会渲染一个自动补全建议弹出框。它适用于以下场景:
div[contenteditable]textarea@- 用户打标签 —— 使用标记人员、团队或资源
@ - 话题标签建议 —— 使用任意自定义字符(、
#等)作为触发器/ - 富文本集成 —— 适配div和各类编辑器
contenteditable - 数据绑定 —— 支持本地数组(字符串、对象、复杂对象)和远程DataManager数据源
- 过滤 —— 支持、
Contains、StartsWith匹配规则,可配置最小触发长度、防抖延迟、空格支持EndsWith - 模板自定义 —— 支持条目、展示、无数据、加载动画、分组模板自定义
- 禁用项 —— 可将单个列表项标记为不可选
- 无障碍适配 —— 符合WCAG 2.2标准,支持全键盘导航和ARIA属性
Key Characteristics
核心特性
| Aspect | Details |
|---|---|
| Trigger | Any single character via |
| Target | Any |
| Data Sources | Local arrays (strings, objects), remote |
| Filtering | Built-in: |
| Display | |
| Suffix | |
| Accessibility | WCAG 2.2, Section 508, ADA; keyboard shortcuts: Arrow keys, Enter, Tab, Escape |
| Localization | |
| 维度 | 详情 |
|---|---|
| 触发字符 | 可通过 |
| 目标元素 | 可通过 |
| 数据源 | 本地数组(字符串、对象)、远程 |
| 过滤规则 | 内置: |
| 展示规则 | |
| 后缀配置 | |
| 无障碍适配 | 符合WCAG 2.2、Section 508、ADA标准;支持快捷键:方向键、回车、Tab、ESC |
| 本地化 | 可通过 |
Documentation Navigation Guide
文档导航指南
📄 Getting Started
📄 快速入门
Read: references/getting-started.md
- Install package
@syncfusion/ej2-angular-dropdowns - Set up Angular 21+ project with standalone components
- Import and required CSS themes
MentionModule - Create a target div
contenteditable - Bind and basic
targetdataSource - Display/customize the mention character with and
showMentionCharmentionChar
阅读: references/getting-started.md
- 安装包
@syncfusion/ej2-angular-dropdowns - 配置Angular 21+独立组件项目
- 引入和所需CSS主题
MentionModule - 创建目标div
contenteditable - 绑定和基础
targetdataSource - 通过和
showMentionChar配置和自定义触发字符mentionChar
📄 Data Binding
📄 数据绑定
Read: references/data-binding.md
- Bind to local arrays of strings, JSON objects, and complex objects
- Map ,
text,value, andgroupByviaiconCsspropertyfields - Remote data with using
DataManagerandODataV4AdaptorWebApiAdaptor - Use the property to scope remote requests
query
阅读: references/data-binding.md
- 绑定字符串、JSON对象、复杂对象类型的本地数组
- 通过属性映射
fields、text、value、groupBy字段iconCss - 结合和
ODataV4Adaptor使用WebApiAdaptor绑定远程数据DataManager - 使用属性限定远程请求的查询范围
query
📄 Filtering
📄 过滤配置
Read: references/filtering.md
- Control filter strategy with (
filterType,Contains,StartsWith)EndsWith - Set minimum input length before triggering with
minLength - Allow spaces in the middle of a mention search with
allowSpaces - Limit visible suggestion count with
suggestionCount - Tune debounce delay for remote sources with
debounceDelay
阅读: references/filtering.md
- 通过控制过滤策略(
filterType、Contains、StartsWith)EndsWith - 通过配置触发建议的最小输入长度
minLength - 通过允许提及搜索中间包含空格
allowSpaces - 通过限制展示的建议条目数量
suggestionCount - 为远程数据源通过调整防抖延迟
debounceDelay
📄 Templates
📄 模板配置
Read: references/templates.md
- Customize suggestion list item layout with
itemTemplate - Customize the inserted text representation with
displayTemplate - Handle empty results with
noRecordsTemplate - Show a loading indicator while fetching remote data with
spinnerTemplate - Customize grouped items with
groupTemplate
阅读: references/templates.md
- 通过自定义建议列表的条目布局
itemTemplate - 通过自定义插入文本的展示形式
displayTemplate - 通过处理无匹配结果的场景
noRecordsTemplate - 通过自定义远程数据加载的加载指示器
spinnerTemplate - 通过自定义分组条目的展示
groupTemplate
📄 Customization
📄 自定义配置
Read: references/customization.md
- Show/hide the trigger character alongside selected text with
showMentionChar - Append a suffix (space, newline) after selection with
suffixText - Resize the popup with and
popupHeightpopupWidth - Change the trigger character with
mentionChar - Control leading space requirement with
requireLeadingSpace - Apply custom CSS classes with
cssClass - Highlight searched characters with
highlight - Configure and
ignoreCasefor search behaviorignoreAccent
阅读: references/customization.md
- 通过控制选中文本是否携带触发字符
showMentionChar - 通过配置选中条目后追加的后缀(空格、换行等)
suffixText - 通过和
popupHeight调整弹出框尺寸popupWidth - 通过修改触发字符
mentionChar - 通过控制触发字符前是否需要前置空格
requireLeadingSpace - 通过应用自定义CSS类
cssClass - 通过高亮匹配的搜索字符
highlight - 配置和
ignoreCase调整搜索行为ignoreAccent
📄 Sorting & Disabled Items
📄 排序与禁用项
Read: references/sorting-and-disabled-items.md
- Sort suggestions with (
sortOrder,None,Ascending)Descending - Mark items as non-selectable via
fields.disabled - Dynamically disable items at runtime using the method
disableItem
阅读: references/sorting-and-disabled-items.md
- 通过配置建议排序规则(
sortOrder、None、Ascending)Descending - 通过标记条目为不可选
fields.disabled - 运行时通过方法动态禁用条目
disableItem
📄 Accessibility & Localization
📄 无障碍与本地化
Read: references/accessibility-and-localization.md
- WCAG 2.2, Section 508, and ADA compliance
- Full keyboard shortcuts (Arrow Down/Up, Enter, Tab, Escape)
- ARIA attributes: ,
aria-selected,aria-activedescendentaria-owns - Localize with
noRecordsTemplateL10n.load() - RTL support with
enableRtl
阅读: references/accessibility-and-localization.md
- 符合WCAG 2.2、Section 508、ADA标准
- 全键盘快捷键支持(上下方向键、回车、Tab、ESC)
- 支持ARIA属性:、
aria-selected、aria-activedescendentaria-owns - 通过实现
L10n.load()本地化noRecordsTemplate - 通过支持从右到左的排版
enableRtl
📄 API Reference
📄 API参考
Read: references/api.md
- Complete properties reference with types, defaults, and descriptions
- All methods: ,
addItem,disableItem,getDataByValue,getItems,hidePopup,showPopup,searchdestroy - All events: ,
dataBoundactionFailureTemplate
阅读: references/api.md
- 完整的属性参考,包含类型、默认值和说明
- 所有方法:、
addItem、disableItem、getDataByValue、getItems、hidePopup、showPopup、searchdestroy - 所有事件:、
dataBoundactionFailureTemplate
Quick Start Example
快速开始示例
typescript
// app.component.ts (Angular 21 Standalone)
import { Component } from '@angular/core';
import { MentionModule } from '@syncfusion/ej2-angular-dropdowns';
@Component({
selector: 'app-root',
standalone: true,
imports: [MentionModule],
template: `
<label style="font-size: 15px; font-weight: 600;">Comments</label>
<div id="mentionElement"
placeholder="Type @ and tag a user"
style="min-height: 100px; border: 1px solid #D7D7D7; border-radius: 4px; padding: 8px;">
</div>
<ejs-mention [dataSource]="userData" [target]="mentionTarget"></ejs-mention>
`
})
export class AppComponent {
public userData: string[] = ['Selma Rose', 'Garth', 'Robert', 'William', 'Joseph'];
public mentionTarget: string = '#mentionElement';
}Install the package:
⚠️ Security note: Pin the package to a specific version to prevent unintended upgrades to potentially compromised releases. Verify the installed version against your lockfile (/package-lock.json) after installation.yarn.lock
bash
ng add @syncfusion/ej2-angular-dropdowns@33.1.44Add CSS ():
styles.css⚠️ Security note: These imports are resolved fromat build time. Ensure the installed Syncfusion packages match your pinned versions innode_modulesorpackage-lock.jsonbefore building. Do not source these files from a CDN without Subresource Integrity (SRI) hashes.yarn.lock
css
@import '../node_modules/@syncfusion/ej2-base/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-buttons/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-popups/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-lists/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-angular-dropdowns/styles/material3.css';typescript
// app.component.ts (Angular 21 Standalone)
import { Component } from '@angular/core';
import { MentionModule } from '@syncfusion/ej2-angular-dropdowns';
@Component({
selector: 'app-root',
standalone: true,
imports: [MentionModule],
template: `
<label style="font-size: 15px; font-weight: 600;">Comments</label>
<div id="mentionElement"
placeholder="Type @ and tag a user"
style="min-height: 100px; border: 1px solid #D7D7D7; border-radius: 4px; padding: 8px;">
</div>
<ejs-mention [dataSource]="userData" [target]="mentionTarget"></ejs-mention>
`
})
export class AppComponent {
public userData: string[] = ['Selma Rose', 'Garth', 'Robert', 'William', 'Joseph'];
public mentionTarget: string = '#mentionElement';
}安装依赖包:
⚠️ 安全提示: 将依赖包固定到特定版本,避免意外升级到可能存在安全风险的版本。安装后对照锁文件(/package-lock.json)验证安装的版本是否符合预期。yarn.lock
bash
ng add @syncfusion/ej2-angular-dropdowns@33.1.44引入CSS():
styles.css⚠️ 安全提示: 这些导入会在构建时从中解析。构建前请确认安装的Syncfusion包和node_modules/package-lock.json中固定的版本一致。不要从CDN引入这些文件,除非配置了子资源完整性(SRI)哈希。yarn.lock
css
@import '../node_modules/@syncfusion/ej2-base/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-buttons/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-popups/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-lists/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-angular-dropdowns/styles/material3.css';Common Patterns
常见使用场景
Pattern 1: Object Data with Field Mapping
场景1:对象数据的字段映射
typescript
public userData: { [key: string]: Object }[] = [
{ Name: 'Selma Rose', EmailId: 'selma@gmail.com' },
{ Name: 'Maria', EmailId: 'maria@gmail.com' },
{ Name: 'Robert', EmailId: 'robert@gmail.com' }
];
public fields: Object = { text: 'Name' };
public mentionTarget: string = '#mentionElement';html
<ejs-mention [dataSource]="userData" [fields]="fields" [target]="mentionTarget"></ejs-mention>typescript
public userData: { [key: string]: Object }[] = [
{ Name: 'Selma Rose', EmailId: 'selma@gmail.com' },
{ Name: 'Maria', EmailId: 'maria@gmail.com' },
{ Name: 'Robert', EmailId: 'robert@gmail.com' }
];
public fields: Object = { text: 'Name' };
public mentionTarget: string = '#mentionElement';html
<ejs-mention [dataSource]="userData" [fields]="fields" [target]="mentionTarget"></ejs-mention>Pattern 2: Custom Trigger Character with showMentionChar
场景2:自定义触发字符并展示触发字符
html
<ejs-mention
[dataSource]="userData"
[target]="mentionTarget"
[mentionChar]="'#'"
[showMentionChar]="true">
</ejs-mention>html
<ejs-mention
[dataSource]="userData"
[target]="mentionTarget"
[mentionChar]="'#'"
[showMentionChar]="true">
</ejs-mention>Pattern 3: Remote Data with Popup Width
场景3:绑定远程数据并配置弹出框宽度
⚠️ Security note: Replace the URL below with your own API endpoint. Avoid enablingunless your server explicitly requires it and you have validated the CORS policy. Always sanitize or restrict user input before it is forwarded to remote sources, and verify installed packages against your lockfile (crossDomain: true/package-lock.json).yarn.lock
typescript
import { DataManager, ODataV4Adaptor, Query } from '@syncfusion/ej2-data';
public searchData: DataManager = new DataManager({
url: 'https://your-api-endpoint.example.com/api/',
adaptor: new ODataV4Adaptor
// crossDomain: true — enable only if your server requires it and CORS is properly configured
});
public query: Query = new Query().from('Customers').select(['ContactName', 'CustomerID']).take(6);
public fields: Object = { text: 'ContactName', value: 'CustomerID' };
public popupWidth: string = '250px';⚠️ 安全提示: 将下方的URL替换为你自己的API接口地址。除非服务器明确需要且你已经验证过CORS策略,否则不要启用。用户输入转发到远程数据源前请务必做 sanitize 或限制处理,同时对照锁文件(crossDomain: true/package-lock.json)验证安装的依赖包版本。yarn.lock
typescript
import { DataManager, ODataV4Adaptor, Query } from '@syncfusion/ej2-data';
public searchData: DataManager = new DataManager({
url: 'https://your-api-endpoint.example.com/api/',
adaptor: new ODataV4Adaptor
// crossDomain: true — 仅当服务器明确需要且CORS配置正确时启用
});
public query: Query = new Query().from('Customers').select(['ContactName', 'CustomerID']).take(6);
public fields: Object = { text: 'ContactName', value: 'CustomerID' };
public popupWidth: string = '250px';Pattern 4: Allow Spaces in Mention Search
场景4:允许提及搜索中包含空格
html
<ejs-mention
[dataSource]="userData"
[fields]="fields"
[allowSpaces]="true"
[target]="mentionTarget">
</ejs-mention>html
<ejs-mention
[dataSource]="userData"
[fields]="fields"
[allowSpaces]="true"
[target]="mentionTarget">
</ejs-mention>Key Properties Quick Reference
核心属性速查
| Property | Type | Default | Purpose |
|---|---|---|---|
| HTMLElement | string | — | Target element where mention suggestions appear |
| Array | DataManager | | Source data for suggestions |
| FieldSettingsModel | | Map data columns to component |
| string | | Character that triggers the suggestion popup |
| boolean | | Show trigger character with inserted text |
| string | | Text appended after the selected item |
| FilterType | | How suggestions are matched |
| number | | Minimum chars to trigger filtering |
| boolean | | Allow spaces in mid-mention search |
| number | | Max number of suggestions shown |
| number | | Delay (ms) before filtering fires |
| SortOrder | | Sort suggestions order |
| string | number | | Popup list height |
| string | number | | Popup list width |
| boolean | | Highlight matched characters |
| boolean | | Case-insensitive search |
| boolean | — | Ignore diacritics in search |
| boolean | | Require space before trigger character |
| string | | Custom CSS class(es) on the component |
| string | | Localization culture |
| boolean | | Right-to-left rendering |
| boolean | | Persist state between reloads |
| number | | Popup z-index |
| 属性 | 类型 | 默认值 | 作用 |
|---|---|---|---|
| HTMLElement | string | — | 触发提及建议的目标元素 |
| Array | DataManager | | 建议的数据源 |
| FieldSettingsModel | | 数据字段和组件字段的映射 |
| string | | 触发建议弹出框的字符 |
| boolean | | 插入的文本是否携带触发字符 |
| string | | 选中条目后追加的文本 |
| FilterType | | 建议的匹配规则 |
| number | | 触发过滤的最小输入字符数 |
| boolean | | 提及搜索中是否允许包含空格 |
| number | | 最多展示的建议条目数量 |
| number | | 过滤触发前的延迟(毫秒) |
| SortOrder | | 建议的排序规则 |
| string | number | | 弹出框高度 |
| string | number | | 弹出框宽度 |
| boolean | | 是否高亮匹配的字符 |
| boolean | | 搜索是否忽略大小写 |
| boolean | — | 搜索是否忽略变音符号 |
| boolean | | 触发字符前是否需要前置空格 |
| string | | 组件上挂载的自定义CSS类 |
| string | | 本地化文化标识 |
| boolean | | 是否启用从右到左的排版 |
| boolean | | 刷新页面时是否保留组件状态 |
| number | | 弹出框的z-index值 |
Workflow Decision Tree
实现流程决策树
Need to implement Mention / @mention tagging?
│
├─ What's your data source?
│ ├─ Local strings/array → See Data Binding: "Array of simple data"
│ ├─ Local objects → See Data Binding: "Array of JSON data" + fields mapping
│ └─ Remote API → See Data Binding: "Binding remote data"
│
├─ Custom trigger character (not @)?
│ └─ YES → [mentionChar]="'#'" (or any single char)
│
├─ Show trigger char in inserted text?
│ └─ YES → [showMentionChar]="true"
│
├─ Multi-word names (e.g., "John Doe")?
│ └─ YES → [allowSpaces]="true"
│
├─ Custom item layout in popup?
│ └─ YES → See Templates: itemTemplate / displayTemplate
│
├─ Need sorted suggestions?
│ └─ YES → See Sorting & Disabled Items: sortOrder
│
├─ Some items should not be selectable?
│ └─ YES → See Sorting & Disabled Items: fields.disabled / disableItem
│
├─ Filtering behavior?
│ ├─ By default (Contains) → No extra config
│ ├─ StartsWith / EndsWith → filterType="StartsWith"
│ └─ Minimum typed chars → [minLength]="3"
│
└─ Need accessibility or localization?
└─ YES → See Accessibility & Localization reference需要实现Mention / @提及标签功能?
│
├─ 你的数据源是什么?
│ ├─ 本地字符串/数组 → 参考数据绑定:「简单数据数组」
│ ├─ 本地对象 → 参考数据绑定:「JSON数据数组」 + 字段映射
│ └─ 远程API → 参考数据绑定:「绑定远程数据」
│
├─ 需要自定义触发字符(不是@)?
│ └─ 是 → [mentionChar]="'#'"(或任意单个字符)
│
├─ 插入文本中需要展示触发字符?
│ └─ 是 → [showMentionChar]="true"
│
├─ 支持多词名称(例如「John Doe」)?
│ └─ 是 → [allowSpaces]="true"
│
├─ 需要自定义弹出框的条目布局?
│ └─ 是 → 参考模板:itemTemplate / displayTemplate
│
├─ 需要对建议进行排序?
│ └─ 是 → 参考排序与禁用项:sortOrder
│
├─ 存在不可选的条目?
│ └─ 是 → 参考排序与禁用项:fields.disabled / disableItem
│
├─ 自定义过滤行为?
│ ├─ 默认规则(包含匹配) → 无需额外配置
│ ├─ 开头匹配 / 结尾匹配 → filterType="StartsWith"
│ └─ 配置最小输入触发长度 → [minLength]="3"
│
└─ 需要无障碍适配或本地化?
└─ 是 → 参考无障碍与本地化文档