• Mention提及
    • 何时使用
    • 代码演示
    • API
      • 单独引入此组件
      • nz-mentioncomponent
        • 方法
      • nzMentionTrigger
      • nzMentionSuggestion
      • MentionOnSearchTypes

    Mention提及

    提及组件。

    何时使用

    用于在输入中提及某人或某事,常用于发布、聊天或评论功能。

    代码演示

    Mention提及 - 图1

    基本使用

    基本使用

    1. import { Component, ViewEncapsulation } from '@angular/core';
    2. @Component({
    3. selector: 'nz-demo-mention-basic',
    4. encapsulation: ViewEncapsulation.None,
    5. template: `
    6. <nz-mention [nzSuggestions]="suggestions" (nzOnSelect)="onSelect($event)">
    7. <input
    8. placeholder="input here"
    9. nzMentionTrigger
    10. nz-input
    11. [(ngModel)]="inputValue"
    12. (ngModelChange)="onChange($event)"
    13. />
    14. </nz-mention>
    15. `
    16. })
    17. export class NzDemoMentionBasicComponent {
    18. inputValue: string = '@afc163';
    19. suggestions = ['afc163', 'benjycui', 'yiminghe', 'RaoHai', '中文', 'にほんご'];
    20. onChange(value: string): void {
    21. console.log(value);
    22. }
    23. onSelect(suggestion: string): void {
    24. console.log(`onSelect ${suggestion}`);
    25. }
    26. }

    Mention提及 - 图2

    异步加载

    匹配内容列表为异步返回时。

    1. import { Component, ViewEncapsulation } from '@angular/core';
    2. import { MentionOnSearchTypes } from 'ng-zorro-antd';
    3. @Component({
    4. selector: 'nz-demo-mention-async',
    5. encapsulation: ViewEncapsulation.None,
    6. template: `
    7. <nz-mention [nzSuggestions]="suggestions" [nzLoading]="loading" (nzOnSearchChange)="onSearchChange($event)">
    8. <input nzMentionTrigger nz-input [(ngModel)]="inputValue" />
    9. </nz-mention>
    10. `
    11. })
    12. export class NzDemoMentionAsyncComponent {
    13. inputValue: string;
    14. loading = false;
    15. suggestions: string[] = [];
    16. onSearchChange({ value }: MentionOnSearchTypes): void {
    17. console.log(`search: ${value}`);
    18. this.loading = true;
    19. this.fetchSuggestions(value, suggestions => {
    20. console.log(suggestions);
    21. this.suggestions = suggestions;
    22. this.loading = false;
    23. });
    24. }
    25. fetchSuggestions(value: string, callback: (suggestions: string[]) => void): void {
    26. const users = ['afc163', 'benjycui', 'yiminghe', 'jljsj33', 'dqaria', 'RaoHai'];
    27. setTimeout(() => {
    28. return callback(users.filter(item => item.indexOf(value) !== -1));
    29. }, 500);
    30. }
    31. }

    Mention提及 - 图3

    头像

    自定义建议(含头像)

    注意,nzSuggestions 不为 string[] 时,需要提供 valueWith

    1. import { Component, ViewEncapsulation } from '@angular/core';
    2. @Component({
    3. selector: 'nz-demo-mention-avatar',
    4. encapsulation: ViewEncapsulation.None,
    5. template: `
    6. <nz-mention [nzSuggestions]="webFrameworks" [nzValueWith]="valueWith" (nzOnSelect)="onSelect($event)">
    7. <input nz-input nzMentionTrigger [(ngModel)]="inputValue" />
    8. <ng-container *nzMentionSuggestion="let framework">
    9. <nz-avatar nzSize="small" [nzText]="framework.name" [nzSrc]="framework.icon"></nz-avatar>
    10. <span>{{ framework.name }} - {{ framework.type }}</span>
    11. </ng-container>
    12. </nz-mention>
    13. `,
    14. styles: [
    15. `
    16. .ant-avatar.ant-avatar-sm {
    17. width: 14px;
    18. height: 14px;
    19. margin-right: 8px;
    20. position: relative;
    21. }
    22. `
    23. ]
    24. })
    25. export class NzDemoMentionAvatarComponent {
    26. inputValue: string;
    27. webFrameworks = [
    28. { name: 'React', type: 'JavaScript', icon: 'https://zos.alipayobjects.com/rmsportal/LFIeMPzdLcLnEUe.svg' },
    29. { name: 'Angular', type: 'JavaScript', icon: 'https://zos.alipayobjects.com/rmsportal/PJTbxSvzYWjDZnJ.png' },
    30. { name: 'Dva', type: 'Javascript', icon: 'https://zos.alipayobjects.com/rmsportal/EYPwSeEJKxDtVxI.png' },
    31. { name: 'Flask', type: 'Python', icon: 'https://zos.alipayobjects.com/rmsportal/xaypBUijfnpAlXE.png' }
    32. ];
    33. valueWith = (data: { name: string; type: string; icon: string }) => data.name;
    34. onSelect(value: string): void {
    35. console.log(value);
    36. }
    37. }

    Mention提及 - 图4

    多行

    多行模式。

    1. import { Component, ViewEncapsulation } from '@angular/core';
    2. @Component({
    3. selector: 'nz-demo-mention-multilines',
    4. encapsulation: ViewEncapsulation.None,
    5. template: `
    6. <nz-mention [nzSuggestions]="suggestions">
    7. <textarea nz-input [nzAutosize]="{ minRows: 4, maxRows: 4 }" [(ngModel)]="inputValue" nzMentionTrigger>
    8. </textarea>
    9. </nz-mention>
    10. `
    11. })
    12. export class NzDemoMentionMultilinesComponent {
    13. inputValue: string;
    14. suggestions = ['afc163', 'benjycui', 'yiminghe', 'RaoHai', '中文', 'にほんご'];
    15. }

    Mention提及 - 图5

    自定义触发字符

    通过 nzPrefix 属性自定义触发字符。默认为 @, 可以定义为数组。

    1. import { Component, ViewEncapsulation } from '@angular/core';
    2. import { MentionOnSearchTypes } from 'ng-zorro-antd';
    3. @Component({
    4. selector: 'nz-demo-mention-multiple-trigger',
    5. encapsulation: ViewEncapsulation.None,
    6. template: `
    7. <nz-mention [nzSuggestions]="suggestions" (nzOnSearchChange)="onSearchChange($event)" [nzPrefix]="['#', '@']">
    8. <input
    9. placeholder="input @ to mention people, # to mention tag"
    10. nzMentionTrigger
    11. nz-input
    12. [(ngModel)]="inputValue"
    13. />
    14. </nz-mention>
    15. `
    16. })
    17. export class NzDemoMentionMultipleTriggerComponent {
    18. inputValue: string;
    19. suggestions: string[] = [];
    20. users = ['afc163', 'benjycui', 'yiminghe', 'RaoHai', '中文', 'にほんご'];
    21. tags = ['1.0', '2.0', '3.0'];
    22. onSearchChange({ value, prefix }: MentionOnSearchTypes): void {
    23. console.log('nzOnSearchChange', value, prefix);
    24. this.suggestions = prefix === '@' ? this.users : this.tags;
    25. }
    26. }

    Mention提及 - 图6

    向上展开

    向上展开建议。

    1. import { Component, ViewEncapsulation } from '@angular/core';
    2. @Component({
    3. selector: 'nz-demo-mention-placement',
    4. encapsulation: ViewEncapsulation.None,
    5. template: `
    6. <nz-mention nzPlacement="top" [nzSuggestions]="suggestions" (nzOnSelect)="onSelect($event)">
    7. <input nzMentionTrigger nz-input [(ngModel)]="inputValue" (ngModelChange)="onChange($event)" />
    8. </nz-mention>
    9. `
    10. })
    11. export class NzDemoMentionPlacementComponent {
    12. inputValue: string;
    13. suggestions = ['afc163', 'benjycui', 'yiminghe', 'RaoHai', '中文', 'にほんご'];
    14. onChange(value: string): void {
    15. console.log(value);
    16. }
    17. onSelect(suggestion: string): void {
    18. console.log(`onSelect ${suggestion}`);
    19. }
    20. }

    Mention提及 - 图7

    自定义建议

    自定义建议

    注意,nzSuggestions 不为 string[] 时,需要提供 valueWith

    1. import { Component, ViewEncapsulation } from '@angular/core';
    2. @Component({
    3. selector: 'nz-demo-mention-custom-tag',
    4. encapsulation: ViewEncapsulation.None,
    5. template: `
    6. <nz-mention [nzSuggestions]="webFrameworks" [nzValueWith]="valueWith" (nzOnSelect)="onSelect($event)">
    7. <input placeholder="@someone" nz-input nzMentionTrigger [(ngModel)]="inputValue" />
    8. <ng-container *nzMentionSuggestion="let framework">
    9. <span>{{ framework.name }} - {{ framework.type }}</span>
    10. </ng-container>
    11. </nz-mention>
    12. `
    13. })
    14. export class NzDemoMentionCustomTagComponent {
    15. inputValue: string;
    16. webFrameworks = [
    17. { name: 'React', type: 'JavaScript' },
    18. { name: 'Angular', type: 'JavaScript' },
    19. { name: 'Laravel', type: 'PHP' },
    20. { name: 'Flask', type: 'Python' },
    21. { name: 'Django', type: 'Python' }
    22. ];
    23. valueWith = (data: { name: string; type: string }) => data.name;
    24. onSelect(value: string): void {
    25. console.log(value);
    26. }
    27. }

    Mention提及 - 图8

    配合 Form 使用

    受控模式,例如配合 Form 使用。

    1. import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
    2. import { AbstractControl, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
    3. @Component({
    4. selector: 'nz-demo-mention-controlled',
    5. encapsulation: ViewEncapsulation.None,
    6. template: `
    7. <form nz-form [formGroup]="validateForm" (ngSubmit)="submitForm()">
    8. <nz-form-item>
    9. <nz-form-label [nzSm]="6" nzFor="mention">Top coders</nz-form-label>
    10. <nz-form-control [nzSm]="16">
    11. <nz-mention #mentions [nzSuggestions]="suggestions">
    12. <input id="mention" placeholder="input here" formControlName="mention" nzMentionTrigger nz-input />
    13. </nz-mention>
    14. <nz-form-explain *ngIf="validateForm.get('mention')?.dirty && validateForm.get('mention')?.errors">
    15. More than one must be selected!
    16. </nz-form-explain>
    17. </nz-form-control>
    18. </nz-form-item>
    19. <nz-form-item nz-row style="margin-bottom:8px;">
    20. <nz-form-control [nzSpan]="14" [nzOffset]="6">
    21. <button type="button" nz-button nzType="primary" (click)="submitForm()">Submit</button>
    22. &nbsp;&nbsp;&nbsp;
    23. <button type="button" nz-button (click)="resetForm()">Reset</button>
    24. </nz-form-control>
    25. </nz-form-item>
    26. </form>
    27. `
    28. })
    29. export class NzDemoMentionControlledComponent implements OnInit {
    30. suggestions = ['afc163', 'benjycui', 'yiminghe', 'RaoHai', '中文', 'にほんご'];
    31. validateForm: FormGroup;
    32. @ViewChild('mentions') mentionChild: any;
    33. get mention(): AbstractControl {
    34. return this.validateForm.get('mention')!;
    35. }
    36. constructor(private fb: FormBuilder) {}
    37. ngOnInit(): void {
    38. this.validateForm = this.fb.group({
    39. mention: ['@afc163 ', [Validators.required, this.mentionValidator]]
    40. });
    41. }
    42. mentionValidator = (control: FormControl): { [s: string]: boolean } => {
    43. if (!control.value) {
    44. return { required: true };
    45. } else if (this.mentionChild.getMentions().length < 2) {
    46. return { confirm: true, error: true };
    47. }
    48. return {};
    49. };
    50. submitForm(): void {
    51. this.mention.markAsDirty();
    52. if (this.mention.valid) {
    53. console.log('Submit!!!', this.mention.value);
    54. console.log(this.mentionChild.getMentions());
    55. } else {
    56. console.log('Errors in form!!!');
    57. }
    58. }
    59. resetForm(): void {
    60. this.validateForm.reset({
    61. mention: '@afc163 '
    62. });
    63. }
    64. }

    Mention提及 - 图9

    无效或只读

    通过 disabled 属性设置是否生效。通过 readOnly 属性设置是否只读。

    1. import { Component, ViewEncapsulation } from '@angular/core';
    2. @Component({
    3. selector: 'nz-demo-mention-readonly',
    4. encapsulation: ViewEncapsulation.None,
    5. template: `
    6. <nz-mention [nzSuggestions]="suggestions">
    7. <input
    8. style="margin-bottom: 10px"
    9. placeholder="this is disabled Mention"
    10. nzMentionTrigger
    11. nz-input
    12. disabled
    13. [(ngModel)]="inputValue"
    14. />
    15. <input placeholder="this is readOnly Mention" nzMentionTrigger nz-input readOnly [(ngModel)]="inputValue" />
    16. </nz-mention>
    17. `
    18. })
    19. export class NzDemoMentionReadonlyComponent {
    20. inputValue: string;
    21. suggestions = ['afc163', 'benjycui', 'yiminghe', 'RaoHai', '中文', 'にほんご'];
    22. }

    Mention提及 - 图10

    预览

    渲染提及

    1. import { Component, ViewEncapsulation } from '@angular/core';
    2. import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
    3. @Component({
    4. selector: 'nz-demo-mention-preview',
    5. encapsulation: ViewEncapsulation.None,
    6. template: `
    7. <nz-tabset>
    8. <nz-tab nzTitle="Write">
    9. <nz-mention [nzSuggestions]="suggestions">
    10. <textarea
    11. nz-input
    12. [nzAutosize]="{ minRows: 4, maxRows: 4 }"
    13. [(ngModel)]="inputValue"
    14. (ngModelChange)="renderPreView()"
    15. nzMentionTrigger
    16. >
    17. </textarea>
    18. </nz-mention>
    19. </nz-tab>
    20. <nz-tab nzTitle="Preview">
    21. <pre [innerHTML]="preview"></pre>
    22. </nz-tab>
    23. </nz-tabset>
    24. `
    25. })
    26. export class NzDemoMentionPreviewComponent {
    27. inputValue: string = 'Switch tab view preview @NG-ZORRO ';
    28. preview: SafeHtml;
    29. suggestions = ['NG-ZORRO', 'angular', 'Reactive-Extensions'];
    30. constructor(private sanitizer: DomSanitizer) {
    31. this.renderPreView();
    32. }
    33. getRegExp(prefix: string | string[]): RegExp {
    34. const prefixArray = Array.isArray(prefix) ? prefix : [prefix];
    35. let prefixToken = prefixArray.join('').replace(/(\$|\^)/g, '\\$1');
    36. if (prefixArray.length > 1) {
    37. prefixToken = `[${prefixToken}]`;
    38. }
    39. return new RegExp(`(\\s|^)(${prefixToken})[^\\s]*`, 'g');
    40. }
    41. renderPreView(): void {
    42. if (this.inputValue) {
    43. const regex = this.getRegExp('@');
    44. const previewValue = this.inputValue.replace(
    45. regex,
    46. match => `<a target="_blank" href="https://github.com/${match.trim().substring(1)}">${match}</a>`
    47. );
    48. this.preview = this.sanitizer.bypassSecurityTrustHtml(previewValue);
    49. }
    50. }
    51. }

    API

    1. <nz-mention [nzSuggestions]="suggestions">
    2. <textarea
    3. nz-input
    4. [(ngModel)]="value"
    5. nzMentionTrigger>
    6. </textarea>
    7. </nz-mention>

    单独引入此组件

    想要了解更多关于单独引入组件的内容,可以在快速上手页面进行查看。

    1. import { NzMentionModule } from 'ng-zorro-antd';

    nz-mentioncomponent

    参数说明类型默认值
    [nzMentionTrigger]用于指定提及的触发元素 (必须)HTMLTextAreaElement|HTMLInputElement-
    [nzMentionSuggestion]自定义建议渲染模板TemplateRef<any>-
    [nzLoading]加载中booleanfalse
    [nzNotFoundContent]未找到时的内容string'无匹配结果,轻敲空格完成输入'
    [nzPlacement]建议框位置'button'|'top''bottom'
    [nzPrefix]触发弹出下拉框的字符string|string[]'@'
    [nzSuggestions]建议内容any[][]
    [nzValueWith]建议选项的取值方法(any) => string|(value: string) => string
    (nzOnSelect)下拉框选择建议时回调EventEmitter<any>-
    (onSearchChange)输入框中 @ 变化时回调EventEmitter<MentionOnSearchTypes>-

    方法

    方法名说明
    getMentions获取 input[nzMentionTrigger] 中的提及数组

    nzMentionTrigger

    用于指定提及的触发元素

    1. <nz-mention>
    2. <textarea nzMentionTrigger></textarea>
    3. </nz-mention>
    1. <nz-mention>
    2. <input nzMentionTrigger>
    3. </nz-mention>

    nzMentionSuggestion

    自定义建议渲染模板

    1. <nz-mention
    2. [nzSuggestions]="items"
    3. [nzValueWith]="valueWith">
    4. <input nz-input nzMentionTrigger>
    5. <ng-container *nzMentionSuggestion="let item">
    6. <span>{{ item.label }} - {{ item.value }}</span>
    7. </ng-container>
    8. </nz-mention>

    MentionOnSearchTypes

    参数说明类型默认值
    value搜索关键词string-
    prefix触发前缀string-