I created a form that makes use of p-editor element to write rich formatted text, but i ran into a problem, the editor creates and submits the rich text, but when we want to update the form with a value from the server, using the angular reactive form patchValue method doesn't update the editor as required. Here is my code
Template:
<form>
<div class="col-12 my-3">
<label class="small font-bold" for="content" i18n>Requirments</label>
<p-editor formControlName="content" id="content" placeholder="content..." [style]="{ height: '200px' }"></p-editor>
</div>
</form>
component:
export class SampleComponent implements OnChanges {
@Input() data?: {content: string};
formEditor: FormGroup
constructor(
private _fb: FormBuilder,
)
{
this.formEditor = this._fb.group({
content: ["", Validators.required]
})
}
ngOnChanges() {
// I verified and indeed the data comes when there is a change
if (this.data) {
this.patchEditorForm(this.data);
}
}
private patchEditorForm = (data: {content: string}) => {
this.formEditor.patchValue({
content: post.content
})
}
}
I use the AfterViewInit and Angular @ViewChild
decorator but it didn't still work
I finally figured out a way around it using the @ViewChild decorator in Angular. Here's how I modified the code to achieve the said objectives:.
import { Component, Input } from '@angular/core';
import { EditorModule, Editor } from 'primeng/editor';
import {
FormBuilder,
FormGroup,
Validators,
ReactiveFormsModule,
} from '@angular/forms';
@Component({
selector: 'app-child',
standalone: true,
imports: [ReactiveFormsModule, EditorModule],
template: `
<form [formGroup]="formEditor">
<div class="col-12 my-3">
<label class="small font-bold" for="content">Content:</label>
<p-editor #editor formControlName="content" id="content" placeholder="content..."></p-editor>
</div>
</form>
`,
})
export class ChildComponent {
@Input() data?: { content: string };
formEditor: FormGroup = new FormGroup({});
// using @ViewChild decorator
@ViewChild('editor') public editor!: Editor
constructor(private _fb: FormBuilder) {
this.formEditor = this._fb.group({
content: ['', Validators.required],
});
}
ngOnChanges() {
// I verified and indeed, the data comes when there is a change
if (this.data) {
// make use of the writeValue() of the editor object
this.editor.writeValue(this.data.content);
}
}
}
Also, make sure you run the command npm install --save @types/quill
, because when trying out this method, I encountered an error with something having to do with an import of Delta
from the library.