如何在contenteditable元素中使用ngControl? [英] How can I use ngControl in contenteditable element?
问题描述
如何在contenteditable
元素中使用ngControl
?
例如,我想要:
How can I use ngControl
in contenteditable
element?
For example, I want:
<!-- *ngFor over rows and columns in table -->
<td contenteditable="true" [ngControl]="row.number + column.number"></td>
通过绑定(?)将其绑定到模型驱动的表单"(表).我根据架构从服务器检索formBuilder
来创建他.
目前,我认为这不起作用,因为<td>
(和其他)元素没有属性value
.然后,可能重载某些方法来使用textContent
属性吗?还是存在其他方法?
With binding (?) it to model-driven "form" (table). I create him with formBuilder
based on schema, that retrieve from server.
Currently I think that doesnt work, 'cause <td>
(and others) element haven't property value
. Then, possible to overload some methods to work with textContent
property? Or exist other way to do this?
谢谢.
推荐答案
要能够将contenteditable
元素与Angular2和控件一起使用,您需要创建一个适用于contenteditable
的自定义指令,该指令必须为ngModel/ngForm兼容,因此您将能够使用ngForm
和ngFormControl
之类的指令.在内部,此指令将注册自定义`Value
To be able to use contenteditable
elements with Angular2 and controls, you need to create a custom directive that applies to the contenteditable
This directive must be ngModel / ngForm compatible so you will be able to use directives like ngForm
and ngFormControl
. Internally this directive will register a custom `Value
这是一个可能的实现方式:
Here is a possible implementation:
const CUSTOM_VALUE_ACCESSOR = CONST_EXPR(new Provider(
NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => ContenteditableAccessor), multi: true}));
@Directive({
selector: '[contenteditable]',
host: {'(blur)': 'onBlur($event)'},
providers: [CUSTOM_VALUE_ACCESSOR]
})
export class ContenteditableAccessor implements ControlValueAccessor {
onChange = (_) => {};
onTouched = () => {};
constructor(private eltRef:ElementRef) {
}
ngOnInit() {
this.onChange(this.eltRef.nativeElement.innerText);
}
writeValue(value: any): void {
if (value!=null) {
this.eltRef.nativeElement.innerText = value;
}
}
onBlur(event) {
this.onChange(this.eltRef.nativeElement.innerText);
}
registerOnChange(fn: (_: any) => void): void { this.onChange = fn; }
registerOnTouched(fn: () => void): void { this.onTouched = fn; }
}
您将可以在组件中以这种方式使用此指令:
You will be able to use this directive this way in a component:
@Component({
selector: 'my-app',
template: `
<div>
<form>
<label>First name:</label>
<span contenteditable="true" [ngFormControl]="testCtrl">Some value</span>
</form>
<div>
firstName: {{testCtrl.value}}<br/>
firstName: {{testCtrl.valid}}<br/>
</div>
<div (click)="updateConditions()">Update conditions</div>
</div>
`,
directives: [ FORM_DIRECTIVES, ContenteditableAccessor ]
})
export class AppComponent {
constructor() {
this.testCtrl = new Control();
}
}
以下是相应的插件: https://plnkr.co/edit/JbjXIa?p=预览.
有关兼容ngForm/ngModel的自定义组件的更多详细信息,可以在"NgModel兼容组件"部分中查看此文章:
For more details about ngForm / ngModel compliant custom components, you could have a look at this article in the section "NgModel-compatible component":
这篇关于如何在contenteditable元素中使用ngControl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!