Code Editor — Angular
@aiao/code-editor-angular 提供 Angular 组件,支持 ControlValueAccessor(ngModel / Reactive Forms)、Signal Input 和丰富的公共方法。
安装
- npm
- Yarn
- pnpm
- Bun
npm install @aiao/code-editor-angular
yarn add @aiao/code-editor-angular
pnpm add @aiao/code-editor-angular
bun add @aiao/code-editor-angular
Peer dependencies: @codemirror/commands, @codemirror/language, @codemirror/state, @codemirror/theme-one-dark, @codemirror/view, codemirror
基础用法
import { CodeEditor } from '@aiao/code-editor-angular';
@Component({
standalone: true,
imports: [CodeEditor],
template: ` <ao-code-editor [value]="code" (aoChange)="onCodeChange($event)" language="typescript" theme="dark" /> `
})
export class MyComponent {
code = 'const x = 1;';
onCodeChange(value: string) {
this.code = value;
}
}
表单集成
Template-driven Forms
<ao-code-editor [(ngModel)]="code" language="sql" />
Reactive Forms
form = new FormGroup({
query: new FormControl('SELECT * FROM users')
});
<ao-code-editor formControlName="query" language="sql" />
ControlValueAccessor
writeValue() 设置值时标记为 External Annotation,不会触发 aoChange 事件,避免循环更新。
组件 API
Selector: ao-code-editor
ChangeDetection: OnPush
Standalone: Yes
Input Properties
| Input | 类型 | 默认值 | 说明 |
|---|---|---|---|
autoFocus | boolean | false | 初始化后自动聚焦 |
disabled | boolean | false | 禁用编辑 |
highlightWhitespace | boolean | false | 高亮空白字符 |
indentUnit | string | '' | 缩进单位 |
indentWithTab | boolean | false | Tab 缩进 |
language | string | '' | 语言名称 |
languages | LanguageDescription[] | SUPPORT_LANGUAGES | 可用语言列表 |
lineWrapping | boolean | false | 自动换行 |
placeholder | string | '' | 占位文本 |
readonly | boolean | false | 只读模式 |
root | Document | ShadowRoot | — | Shadow DOM 根节点 |
setup | 'basic' | 'minimal' | null | 'basic' | 预设扩展包 |
theme | CodeEditorTheme | 'light' | 主题 |
value | string | '' | 编辑器内容 |
Output Events
| Output | 类型 | 说明 |
|---|---|---|
aoChange | EventEmitter<string> | 内容变化(不含 writeValue) |
aoFocus | EventEmitter<void> | 获得焦点 |
aoBlur | EventEmitter<void> | 失去焦点 |
公共方法
| 方法 | 签名 | 说明 |
|---|---|---|
setValue | (value: string, external?: boolean) => void | 设置内容 |
setEditable | (value: boolean) => void | 设置可编辑 |
setReadonly | (value: boolean) => void | 设置只读 |
setTheme | (value: CodeEditorTheme) => void | 切换主题 |
setPlaceholder | (value: string) => void | 设置占位文本 |
setIndentWithTab | (value: boolean) => void | 切换 Tab 缩进 |
setIndentUnit | (value: string) => void | 设置缩进单位 |
setLineWrapping | (value: boolean) => void | 设置换行 |
setHighlightWhitespace | (value: boolean) => void | 空白字符高亮 |
setLanguage | (lang: string) => void | 切换语言 |
setExtensions | (value: Extension[]) => void | 替换所有扩展 |
Angular 特有功能
- Signal Input:所有 input 使用
input()Signal 定义 - SSR 安全:
isPlatformBrowser守卫,服务端不初始化编辑器 - 自定义语言列表:通过
languagesinput 限制可用语言 - Shadow DOM 支持:通过
rootinput 指定挂载根节点 - setup=null:完全无预设扩展,通过
setExtensions()自定义