角度自定义控件内容可编辑,如何连接ngModel


<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编辑内容。问题是数据绑定到了news.columns,如上所示。当用户进行更改时,我可以通过以下结构看到它们:

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

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

任何关于获取bindind内容以重新影响更改的建议,例如,每个news.column都应该有经过编辑的内容。

我怀疑您需要做更多的实现。contenteditable不是一个有角度的东西,它是一个指定元素可编辑的HTML属性。我可能错了,但我认为这与angular的绑定无关。我搜索了Angular.io,"contenteditable"在文档中的点击率为零。

幸运的是,似乎有一些例子可以说明如何为此创建指令,而且似乎许多模块(角度提及(都为您提供了这些内容。

以下是我在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.

最新更新