Angular 自定义控件 contenteditable,如何连接 ngModel?

标签 angular

<button (click)="onSaveChanges()">Save Changes</button>
<section>
  <news-column *ngFor="let column of news.columns">
    <news-header>
      <h2 contenteditable="true" spellcheck="true">
        {{ column.header }}
      </h2>
    </news-header>
    <news-content contenteditable="true" spellcheck="true">
      {{ column.content }}
    </news-content>
    <news-read-more contenteditable="true">
      {{ column.readmore.text }}
    </news-read-more>
    <news-photo contenteditable="true">{{ column.photo.url }} </news-photo>
  </news-column>
</section>

我允许用户使用 contenteditable 编辑内容。问题是数据绑定(bind)到 news.columns,如上所示。当用户进行更改时,我可以通过此构造看到它们:

     ele.addEventListener("input", event => {
          let change = event.target as HTMLElement;
          console.log(change.innerText);
        });

但是当查看 news.column 绑定(bind)时,没有发现任何变化。传统的方法是添加 [ngModel] 等。但是 ngModel 只适用于输入元素。不是任何可内容编辑的元素。我希望更改发生在绑定(bind)中,但正如前面提到的,我可以在 DOM 层看到更改。

有关获取绑定(bind)内容以反射(reflect)更改的任何建议,例如每个 news.column 都应该有编辑过的内容。

最佳答案

我怀疑你需要做更多的实现。 contenteditable 不是一个 Angular 东西,它是一个 HTML 属性,指定元素是可编辑的。我可能是错的,但我不认为这与 Angular 绑定(bind)有任何关系。我搜索了 Angular.io,发现“contenteditable”在文档中的点击率为零。

幸运的是,似乎有一些关于如何为此创建指令的示例,并且似乎许多模块( Angular 提及)都为您包装了它。

以下是我在 GitHub 上搜索“contenteditable Angular”时半随机挑选的两个示例:

https://github.com/KostyaTretyak/ng-stack/tree/master/projects/contenteditable

https://github.com/TinkoffCreditSystems/angular-contenteditable-accessor

如果您查找一些代码,您会发现同样的事情:创建一个管理内容更新的指令,例如:

/*
 * This is a barebones contenteditable {@link ControlValueAccessor} allowing you to use
 * Angular forms with native contenteditable HTML. For security reasons you might want
 * to consider sanitizing pasted/dropped content before using it. Also make sure that
 * you do not set any dangerous content as control value yourself, because directive
 * just outputs control value as-is.
 */
@Directive({
    selector:
        '[contenteditable][formControlName], [contenteditable][formControl], [contenteditable][ngModel]',
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => ContenteditableValueAccessor),
            multi: true,
        },
    ],
})
etc. etc.

关于Angular 自定义控件 contenteditable,如何连接 ngModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60608113/

相关文章:

angular - 在 Angular 4 中为 ngx-datatable 设置固定高度

angular - 如何使 ionic 导航透明?

angular - 如何运行在后台运行 HTMLElement 的 focus() 方法的 Karma jasmine 测试?

javascript - 如何在单击 JavaScript/Angular 时切换字体大小

Angular ionic 构建 : Cannot read property 'toLowerCase' of undefined postcss

node.js - 使用 Angular 和 Express 的 CORS - 在 Postman 中工作,但不在浏览器中工作

angular - 是否需要根据 fromEvent 取消订阅事件

ios - PWA 应用程序 - 使用 Angular 6 在本地存储中存储图像和视频

typescript - 与路由器 socket 的 Angular2 组件通信

javascript - 保留点击 Angular ngFor的背景边框