syncfusion-angular-mention

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Implementing 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
div[contenteditable]
,
textarea
, or similar). It is designed for:
  1. User tagging — tag people, teams, or resources using
    @
  2. Hashtag suggestions — use any custom character (
    #
    ,
    /
    , etc.) as the trigger
  3. Rich text integration — works with
    contenteditable
    divs and editors
  4. Data binding — supports local arrays (strings, objects, complex objects) and remote DataManager sources
  5. Filtering
    Contains
    ,
    StartsWith
    ,
    EndsWith
    with configurable min-length, debounce, and spacing
  6. Template customization — item, display, no-records, spinner, and group templates
  7. Disabled items — mark individual list items as non-selectable
  8. Accessibility — WCAG 2.2 compliant with full keyboard navigation and ARIA attributes
当用户在目标元素(
div[contenteditable]
textarea
或类似元素)中输入触发字符(默认为
@
)时,Mention组件会渲染一个自动补全建议弹出框。它适用于以下场景:
  1. 用户打标签 —— 使用
    @
    标记人员、团队或资源
  2. 话题标签建议 —— 使用任意自定义字符(
    #
    /
    等)作为触发器
  3. 富文本集成 —— 适配
    contenteditable
    div和各类编辑器
  4. 数据绑定 —— 支持本地数组(字符串、对象、复杂对象)和远程DataManager数据源
  5. 过滤 —— 支持
    Contains
    StartsWith
    EndsWith
    匹配规则,可配置最小触发长度、防抖延迟、空格支持
  6. 模板自定义 —— 支持条目、展示、无数据、加载动画、分组模板自定义
  7. 禁用项 —— 可将单个列表项标记为不可选
  8. 无障碍适配 —— 符合WCAG 2.2标准,支持全键盘导航和ARIA属性

Key Characteristics

核心特性

AspectDetails
TriggerAny single character via
mentionChar
(default
@
)
TargetAny
HTMLElement
or CSS selector string set via
target
Data SourcesLocal arrays (strings, objects), remote
DataManager
(OData, Web API)
FilteringBuilt-in:
Contains
,
StartsWith
,
EndsWith
; configurable
minLength
,
allowSpaces
Display
showMentionChar
controls whether the trigger character is shown with selected text
Suffix
suffixText
appends a space or newline after the selected item
AccessibilityWCAG 2.2, Section 508, ADA; keyboard shortcuts: Arrow keys, Enter, Tab, Escape
Localization
L10n.load()
for
noRecordsTemplate
locale key

维度详情
触发字符可通过
mentionChar
配置任意单个字符,默认
@
目标元素可通过
target
配置任意
HTMLElement
或CSS选择器
数据源本地数组(字符串、对象)、远程
DataManager
(OData、Web API)
过滤规则内置:
Contains
StartsWith
EndsWith
;可配置
minLength
allowSpaces
展示规则
showMentionChar
控制选中的文本是否携带触发字符
后缀配置
suffixText
可配置选中条目后追加的空格、换行等内容
无障碍适配符合WCAG 2.2、Section 508、ADA标准;支持快捷键:方向键、回车、Tab、ESC
本地化可通过
L10n.load()
配置
noRecordsTemplate
等文案的多语言

Documentation Navigation Guide

文档导航指南

📄 Getting Started

📄 快速入门

Read: references/getting-started.md
  • Install
    @syncfusion/ej2-angular-dropdowns
    package
  • Set up Angular 21+ project with standalone components
  • Import
    MentionModule
    and required CSS themes
  • Create a target
    contenteditable
    div
  • Bind
    target
    and basic
    dataSource
  • Display/customize the mention character with
    showMentionChar
    and
    mentionChar
阅读: references/getting-started.md
  • 安装
    @syncfusion/ej2-angular-dropdowns
  • 配置Angular 21+独立组件项目
  • 引入
    MentionModule
    和所需CSS主题
  • 创建目标
    contenteditable
    div
  • 绑定
    target
    和基础
    dataSource
  • 通过
    showMentionChar
    mentionChar
    配置和自定义触发字符

📄 Data Binding

📄 数据绑定

Read: references/data-binding.md
  • Bind to local arrays of strings, JSON objects, and complex objects
  • Map
    text
    ,
    value
    ,
    groupBy
    , and
    iconCss
    via
    fields
    property
  • Remote data with
    DataManager
    using
    ODataV4Adaptor
    and
    WebApiAdaptor
  • Use the
    query
    property to scope remote requests
阅读: 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
    popupHeight
    and
    popupWidth
  • Change the trigger character with
    mentionChar
  • Control leading space requirement with
    requireLeadingSpace
  • Apply custom CSS classes with
    cssClass
  • Highlight searched characters with
    highlight
  • Configure
    ignoreCase
    and
    ignoreAccent
    for search behavior
阅读: references/customization.md
  • 通过
    showMentionChar
    控制选中文本是否携带触发字符
  • 通过
    suffixText
    配置选中条目后追加的后缀(空格、换行等)
  • 通过
    popupHeight
    popupWidth
    调整弹出框尺寸
  • 通过
    mentionChar
    修改触发字符
  • 通过
    requireLeadingSpace
    控制触发字符前是否需要前置空格
  • 通过
    cssClass
    应用自定义CSS类
  • 通过
    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
    disableItem
    method
阅读: 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-activedescendent
    ,
    aria-owns
  • Localize
    noRecordsTemplate
    with
    L10n.load()
  • RTL support with
    enableRtl
阅读: references/accessibility-and-localization.md
  • 符合WCAG 2.2、Section 508、ADA标准
  • 全键盘快捷键支持(上下方向键、回车、Tab、ESC)
  • 支持ARIA属性:
    aria-selected
    aria-activedescendent
    aria-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
    ,
    search
    ,
    destroy
  • All events:
    dataBound
    ,
    actionFailureTemplate

阅读: references/api.md
  • 完整的属性参考,包含类型、默认值和说明
  • 所有方法:
    addItem
    disableItem
    getDataByValue
    getItems
    hidePopup
    showPopup
    search
    destroy
  • 所有事件:
    dataBound
    actionFailureTemplate

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
/
yarn.lock
) after installation.
bash
ng add @syncfusion/ej2-angular-dropdowns@33.1.44
Add CSS (
styles.css
):
⚠️ Security note: These imports are resolved from
node_modules
at build time. Ensure the installed Syncfusion packages match your pinned versions in
package-lock.json
or
yarn.lock
before building. Do not source these files from a CDN without Subresource Integrity (SRI) hashes.
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
):
⚠️ 安全提示: 这些导入会在构建时从
node_modules
中解析。构建前请确认安装的Syncfusion包和
package-lock.json
/
yarn.lock
中固定的版本一致。不要从CDN引入这些文件,除非配置了子资源完整性(SRI)哈希。
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 enabling
crossDomain: true
unless 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 (
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策略,否则不要启用
crossDomain: true
。用户输入转发到远程数据源前请务必做 sanitize 或限制处理,同时对照锁文件(
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

核心属性速查

PropertyTypeDefaultPurpose
target
HTMLElement | stringTarget element where mention suggestions appear
dataSource
Array | DataManager
[]
Source data for suggestions
fields
FieldSettingsModel
{ text: null, value: null }
Map data columns to component
mentionChar
string
'@'
Character that triggers the suggestion popup
showMentionChar
boolean
false
Show trigger character with inserted text
suffixText
string
null
Text appended after the selected item
filterType
FilterType
'Contains'
How suggestions are matched
minLength
number
0
Minimum chars to trigger filtering
allowSpaces
boolean
false
Allow spaces in mid-mention search
suggestionCount
number
25
Max number of suggestions shown
debounceDelay
number
300
Delay (ms) before filtering fires
sortOrder
SortOrder
'None'
Sort suggestions order
popupHeight
string | number
'300px'
Popup list height
popupWidth
string | number
'auto'
Popup list width
highlight
boolean
false
Highlight matched characters
ignoreCase
boolean
true
Case-insensitive search
ignoreAccent
booleanIgnore diacritics in search
requireLeadingSpace
boolean
true
Require space before trigger character
cssClass
string
null
Custom CSS class(es) on the component
locale
string
'en-US'
Localization culture
enableRtl
boolean
false
Right-to-left rendering
enablePersistence
boolean
false
Persist state between reloads
zIndex
number
1000
Popup z-index

属性类型默认值作用
target
HTMLElement | string触发提及建议的目标元素
dataSource
Array | DataManager
[]
建议的数据源
fields
FieldSettingsModel
{ text: null, value: null }
数据字段和组件字段的映射
mentionChar
string
'@'
触发建议弹出框的字符
showMentionChar
boolean
false
插入的文本是否携带触发字符
suffixText
string
null
选中条目后追加的文本
filterType
FilterType
'Contains'
建议的匹配规则
minLength
number
0
触发过滤的最小输入字符数
allowSpaces
boolean
false
提及搜索中是否允许包含空格
suggestionCount
number
25
最多展示的建议条目数量
debounceDelay
number
300
过滤触发前的延迟(毫秒)
sortOrder
SortOrder
'None'
建议的排序规则
popupHeight
string | number
'300px'
弹出框高度
popupWidth
string | number
'auto'
弹出框宽度
highlight
boolean
false
是否高亮匹配的字符
ignoreCase
boolean
true
搜索是否忽略大小写
ignoreAccent
boolean搜索是否忽略变音符号
requireLeadingSpace
boolean
true
触发字符前是否需要前置空格
cssClass
string
null
组件上挂载的自定义CSS类
locale
string
'en-US'
本地化文化标识
enableRtl
boolean
false
是否启用从右到左的排版
enablePersistence
boolean
false
刷新页面时是否保留组件状态
zIndex
number
1000
弹出框的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"
└─ 需要无障碍适配或本地化?
    └─ 是 → 参考无障碍与本地化文档