How to Work With a Text Editor in an Angular 8 Application
Join the DZone community and get the full member experience.
Join For FreeIntroduction
In this article, we will learn how to add a text editor in an Angular 8 application. The text editor is a program for adding and editing text. In this demo, we will use an ng2-ckeditor editor. Learn more about Cheditor with their official docs.
Prerequisites
- Basic Knowledge of Angular 2 or higher.
- Visual Studio Code.
- SQL Server Management studio.
- Node and NPM installed.
- Bootstrap.
Step 1
Create an Angular project by using the following command:
ng new TextEditor
Step 2
Open this project in Visual Studio Code and install Bootstrap by using the following command:
xxxxxxxxxx
npm install bootstrap --save
Now, open the styles.css file and add a Bootstrap file reference. To add a reference in the styles.css file, add this line:
xxxxxxxxxx
@import '~bootstrap/dist/css/bootstrap.min.css';
You may also like: Angular: Everything You Need to Know [Tutorials].
Step 3
Now, install the ng2-ckeditor library in this project. To install the ng2-ckeditor library use the following command:
xxxxxxxxxx
npm install ng2-ckeditor
Now, add the CKEditor JavaScript reference in the index.html file by opening the index.html file and adding the following line:
-
TypeScript
xxxxxxxxxx
1
1<script src="https://cdn.ckeditor.com/4.9.2/full-all/ckeditor.js"></script>
Step 4
Now, include the CKEditorModule
in the app.module.ts file.
xxxxxxxxxx
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CKEditorModule } from 'ng2-ckeditor';
import { TextEditorComponent } from './text-editor/text-editor.component';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { PagecontentComponent } from './pagecontent/pagecontent.component';
@NgModule({
declarations: [
AppComponent,
TextEditorComponent,
PagecontentComponent
],
imports: [
BrowserModule,
AppRoutingModule,
CKEditorModule,
HttpClientModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Step 5
Now, create a service to call the Web API by using the following command:
ng g s Content
Now, add the following line in the Content.service.ts file:
xxxxxxxxxx
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ContentService {
url :any;
constructor(private http: HttpClient) { }
AddUpdateContent(pagecontent) {
debugger
this.url = 'http://localhost:56357/Api/Contents/saveconetnt';
return this.http.post(this.url, pagecontent);
}
Getcontent() {
debugger
this.url = 'http://localhost:56357/Api/Contents/Getpagdata';
return this.http.get(this.url);
}
GetcontentById(Id) {
debugger
this.url = 'http://localhost:56357/Api/Contents/GetpagecontentBy?Id='+Id;
return this.http.get(this.url);
}
}
Step 6
Create a class named, "Content," with the following code:
xxxxxxxxxx
export class Content {
Id:number;
Title:string;
Content:string;
}
Step 7
Now, let's create three new components by using the following commands:
Texteditor
.Pagecontent
.detailspost
.
xxxxxxxxxx
ng g c Texteditor
ng g c pagecontent
ng g c detailspost
Step 8
Now, open the texteditor.component.html file and add the following HTML code to design the registration form:
xxxxxxxxxx
<form role="form" #myForm="ngForm" accept-charset="UTF-8" (ngSubmit)="onSubmit()" novalidate style="margin: 30px;">
<div class="form-group">
<input autofocus autocomplete="none" type="text" name="UserName" placeholder="Enter Title"
[(ngModel)]="contentdata.Title" class="form-control" required #PageContentTitle="ngModel"
id="PageContentTitle">
</div>
<ckeditor [(ngModel)]="contentdata.Content" #PageContent="ngModel" name="PageContent" required
[config]="ckeConfig" debounce="500">
</ckeditor>
<div class="form-group mt-4">
<div class="row">
<div class="col-3 col-md-3 mb-3">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</div>
</div>
</form>
Open the texteditor.componet.ts file and add the following lines:
xxxxxxxxxx
import { Component, OnInit, ViewChild ,ElementRef} from '@angular/core';
import { ContentService } from "../content.service";
import { Content } from "../content";
import { FormGroup, FormBuilder, Validators, NgForm } from '@angular/forms';
import { Router } from '@angular/router';
@Component({
selector: 'app-text-editor',
templateUrl: './text-editor.component.html',
styleUrls: ['./text-editor.component.css']
})
export class TextEditorComponent implements OnInit {
name = 'ng2-ckeditor';
ckeConfig: any;
mycontent: string;
log: string
@ViewChild('PageContent') PageContent: any;
res: any;
constructor(private contentservice:ContentService,private router: Router) { }
contentdata=new Content();
ngOnInit() {
this.Getcontent()
this.ckeConfig = {
allowedContent: false,
extraPlugins: 'divarea',
forcePasteAsPlainText: true
};
}
onSubmit()
{
debugger;
debugger;
this.contentservice.AddUpdateContent(this.contentdata).subscribe((data : any) => {
debugger;
alert("Data saved Successfully");
this.router.navigate(['/Post']);
})
}
Getcontent()
{
this.contentservice.Getcontent().subscribe((data:any)=>{
this.res=data;
console.log(this.res);
})
}
}
Step 9
Now, open pagecontent.component.html and add the following HTML:
xxxxxxxxxx
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Title</th>
<th scope="col">Content</th>
<th scope="col">Details</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of res">
<th scope="row">{{data.Id}}</th>
<td>{{data.Title}}</td>
<td>{{data.Content}}</td>
<td> <button (click)="GetcontentById(data.Id)" type="submit" class="btn btn-info">Details</button></td>
</tr>
</tbody>
</table>
Open the pagecontent.componet.ts file and add the following lines:
xxxxxxxxxx
import { Component, OnInit } from '@angular/core';
import { ContentService } from "../content.service";
import { Router } from '@angular/router';
@Component({
selector: 'app-pagecontent',
templateUrl: './pagecontent.component.html',
styleUrls: ['./pagecontent.component.css']
})
export class PagecontentComponent implements OnInit {
res: any;
terms: any;
cont: any;
constructor(private contentservice:ContentService,private router: Router) { }
ngOnInit() {
this.Getcontent()
}
Getcontent()
{
this.contentservice.Getcontent().subscribe((data:any)=>{
this.res=data;
this.terms= this.res[1].pageContentTitle;
this.cont= this.res[1].Content;
console.log(this.res);
})
}
GetcontentById(id:number)
{
this.router.navigate(['/Details'], { queryParams: { Id: id } });
}
}
Step 10
Now, open detailspost.component.html and add the following HTML:
xxxxxxxxxx
<div>
<div>
<h5 style="color:orange;text-align: center">{{this.Title}}</h5>
<hr style="color: blue;">
<span>
<div style="color:#788594" [innerHTML]="this.content"></div>
</span>
</div>
</div>
Open detailspost.componet.ts file and add the following lines:
xxxxxxxxxx
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { ContentService } from '../content.service';
@Component({
selector: 'app-detailspost',
templateUrl: './detailspost.component.html',
styleUrls: ['./detailspost.component.css']
})
export class DetailspostComponent implements OnInit {
res: any;
Title: any;
content: any;
constructor( private route: ActivatedRoute,private contentservice:ContentService) { }
ngOnInit() {
let Id = this.route.snapshot.queryParams["Id"]
this.GetcontentById(Id);
}
GetcontentById(Id:string)
{
this.contentservice.GetcontentById(Id).subscribe((data: any)=>{
this.res=data;
this.Title=this.res.Title
this.content=this.res.Content
console.log(this.res);
});
}
}
Step 11
Now, open the app-routing.module.ts file and add the following lines to create routing:
xxxxxxxxxx
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { PagecontentComponent } from './pagecontent/pagecontent.component';
import { TextEditorComponent } from './text-editor/text-editor.component';
import { DetailspostComponent } from './detailspost/detailspost.component';
const routes: Routes = [
{ path: '', component: TextEditorComponent },
{ path: 'Post', component: PagecontentComponent },
{ path: 'Details', component: DetailspostComponent }
]
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Step 12 — Create a new Web API Project
Open Visual Studio and create a new project.
Change the name to Texteditor.
Select Web API as the template.
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
Click on the ADO.NET Entity Data Model option and click Add.
Select EF Designer from the database and click the Next button and add the connection properties. Select the database name on the next page and click OK.
Check the Table checkbox. The internal options will be selected by default. Now, click on the Finish button.
Our data model is created now.
Step 13
Right-click on the Models folder and add a class Response
. Now, paste the following code in the class.
xxxxxxxxxx
public class Response
{
public string Status { get; set; }
public string Message { get; set; }
}
Right-click the Controllers folder and add a new controller. Name it "Content controller" and add the following namespace in the Content controller.
x
using TextEditor.Models;
Now, add a method to insert and update data into the database.
Step 14 - Complete Content Controller Code
xxxxxxxxxx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TextEditor.Models;
namespace TextEditor.Controllers
{
public class ContentsController : ApiController
{
[HttpPost]
public object saveconetnt(Content Con)
{
try
{
dbCoreEntities2 db = new dbCoreEntities2();
Post Em = new Post();
if (Em.Id == 0)
{
Em.Content = Con.PageContent;
Em.Title =Con.PageContentTitle ;
db.Posts.Add(Em);
db.SaveChanges();
return new Response
{ Status = "Success", Message = "SuccessFully Saved." };
}
}
catch (Exception ex)
{
throw;
}
return new Response
{ Status = "Error", Message = "Invalid Data." };
}
[Route("Api/Contents/Getpagdata")]
[HttpGet]
public object Getpagecontent()
{
dbCoreEntities2 db = new dbCoreEntities2();
return db.Posts.ToList();
}
//[Route("Api/Login/")]
[HttpGet]
public object GetpagecontentById(int id)
{
dbCoreEntities2 db = new dbCoreEntities2();
var obj = db.Posts.Where(x => x.Id == id).ToList().FirstOrDefault();
return obj;
}
}
}
Step 15
Now, let's enable CORS. Go to Tools, open NuGet Package Manager, search for CORS, and install the Microsoft.Asp.Net.WebApi.Cors package. Open the Webapiconfig.cs file and add the following lines:
xxxxxxxxxx
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
Step 16
Now, go to Visual Studio Code and run the project by using the following command: npm start
.
Enter some values, add styles to the text, and click on the submit button.
Click on the details button and check the output. You should have something like the following image.
Summary
In this article, we learned how we integrate a text editor in an Angular application.
Further Reading
Opinions expressed by DZone contributors are their own.
Comments