This is micro Angular v4+ contenteditable directive for compatibility with Angular forms. It just implements ControlValueAccessor for this purpose.
You can just copy and paste this directive or install it from npm:
npm install ng-contenteditable --save
Import and add ContenteditableDirective
to your module:
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ContenteditableDirective } from 'ng-contenteditable';
// ...
@NgModule({
declarations: [
ContenteditableDirective
],
imports: [
// Import one or both of this modules
FormsModule,
ReactiveFormsModule
]
// ...
})
And then you can to use it in template-driven forms like this:
<form #testForm="ngForm">
<p
contenteditable="true"
name="myFormName"
[(ngModel)]="'This is contenteditable text for template form'"
></p>
</form>
<pre>
{{ testForm.value | json }}
</pre>
You can also use reactive forms like this:
// In your component
import { FormControl } from '@angular/forms';
export class MyComponent {
myControl = new FormControl;
ngOnInit()
{
this.myControl.setValue(`This is contenteditable text for reactive form`);
}
}
<p contenteditable="true" [formControl]="myControl"></p>
<pre>
{{ myControl.value | json }}
</pre>
With contenteditable
directive you can pass optional @Input
value for propValueAccessor
:
<p
contenteditable="true"
propValueAccessor="innerHTML"
[formControl]="myControl"
></p>
In ContenteditableDirective
this value use like this:
this.elementRef.nativeElement[this.propValueAccessor]
By default it using textContent
.