DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

Trending

  • File Upload Security and Malware Protection
  • Tactics and Strategies on Software Development: How To Reach Successful Software [Video]
  • Constructing Real-Time Analytics: Fundamental Components and Architectural Framework — Part 2
  • 10 Traits That Separate the Best Devs From the Crowd

Trending

  • File Upload Security and Malware Protection
  • Tactics and Strategies on Software Development: How To Reach Successful Software [Video]
  • Constructing Real-Time Analytics: Fundamental Components and Architectural Framework — Part 2
  • 10 Traits That Separate the Best Devs From the Crowd
  1. DZone
  2. Coding
  3. JavaScript
  4. How to Work With a Text Editor in an Angular 8 Application

How to Work With a Text Editor in an Angular 8 Application

Sanwar ranwa user avatar by
Sanwar ranwa
CORE ·
Jan. 08, 20 · Tutorial
Like (3)
Save
Tweet
Share
26.12K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

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:

TypeScript




x


 
1
ng new TextEditor  



Step 2

Open this project in Visual Studio Code and install Bootstrap by using the following command:

TypeScript




xxxxxxxxxx
1


 
1
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:

TypeScript




xxxxxxxxxx
1


 
1
@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:

TypeScript




xxxxxxxxxx
1


 
1
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.

Importing the CKEditorModule 
TypeScript




xxxxxxxxxx
1
28


 
1
import { BrowserModule } from '@angular/platform-browser';  
2
import { NgModule } from '@angular/core';  
3
import { AppRoutingModule } from './app-routing.module';  
4
import { AppComponent } from './app.component';  
5
import { CKEditorModule } from 'ng2-ckeditor';  
6
import { TextEditorComponent } from './text-editor/text-editor.component';  
7
import { HttpClientModule } from '@angular/common/http';  
8
import { FormsModule, ReactiveFormsModule } from '@angular/forms';  
9
import { PagecontentComponent } from './pagecontent/pagecontent.component';  
10
@NgModule({  
11
  declarations: [  
12
    AppComponent,  
13
    TextEditorComponent,  
14
    PagecontentComponent  
15
  ],  
16
  imports: [  
17
    BrowserModule,  
18
    AppRoutingModule,  
19
    CKEditorModule,  
20
    HttpClientModule,  
21
    FormsModule,  
22
    ReactiveFormsModule  
23
  
24
  ],  
25
  providers: [],  
26
  bootstrap: [AppComponent]  
27
})  
28
export class AppModule { }  



Step 5

 Now, create a service to call the Web API by using the following command:

Shell




x


 
1
ng g s Content  



Now, add the following line in the Content.service.ts file:

TypeScript




xxxxxxxxxx
1
24


 
1
import { Injectable } from '@angular/core';  
2
import { HttpClient } from '@angular/common/http';  
3
@Injectable({  
4
  providedIn: 'root'  
5
})  
6
export class ContentService {  
7
  url :any;  
8
  constructor(private http: HttpClient) { }  
9
  AddUpdateContent(pagecontent) {  
10
    debugger  
11
    this.url = 'http://localhost:56357/Api/Contents/saveconetnt';  
12
    return this.http.post(this.url, pagecontent);  
13
}  
14
Getcontent() {  
15
  debugger  
16
  this.url = 'http://localhost:56357/Api/Contents/Getpagdata';  
17
  return this.http.get(this.url);  
18
}  
19
GetcontentById(Id) {  
20
  debugger  
21
  this.url = 'http://localhost:56357/Api/Contents/GetpagecontentBy?Id='+Id;  
22
  return this.http.get(this.url);  
23
}  
24
}  



Step 6

Create a class named, "Content," with the following code:

TypeScript




xxxxxxxxxx
1


 
1
export class Content {  
2
    Id:number;  
3
    Title:string;  
4
    Content:string;  
5
}  



Step 7

Now, let's create three new components by using the following commands:

  1. Texteditor.
  2. Pagecontent.
  3. detailspost.
Shell




xxxxxxxxxx
1


 
1
ng g c Texteditor   
2
ng g c pagecontent   
3
ng g c detailspost   



Step 8

Now, open the texteditor.component.html file and add the following HTML code to design the registration form:

Java




xxxxxxxxxx
1
17


 
1
<form role="form" #myForm="ngForm" accept-charset="UTF-8" (ngSubmit)="onSubmit()" novalidate style="margin: 30px;">    
2
    <div class="form-group">    
3
        <input autofocus autocomplete="none" type="text" name="UserName" placeholder="Enter Title"    
4
            [(ngModel)]="contentdata.Title" class="form-control" required #PageContentTitle="ngModel"    
5
            id="PageContentTitle">    
6
    </div>    
7
    <ckeditor [(ngModel)]="contentdata.Content" #PageContent="ngModel" name="PageContent" required    
8
        [config]="ckeConfig" debounce="500">    
9
    </ckeditor>    
10
    <div class="form-group mt-4">    
11
        <div class="row">    
12
            <div class="col-3 col-md-3 mb-3">    
13
                <button type="submit" class="btn btn-info">Submit</button>    
14
            </div>    
15
        </div>    
16
    </div>    
17
</form>  


  

Open the texteditor.componet.ts file and add the following lines:

TypeScript




xxxxxxxxxx
1
49


 
1
import { Component, OnInit, ViewChild ,ElementRef} from '@angular/core';    
2
import { ContentService } from "../content.service";     
3
import { Content } from "../content";    
4
import { FormGroup, FormBuilder, Validators, NgForm } from '@angular/forms';    
5
import { Router } from '@angular/router';    
6
    
7
@Component({    
8
  selector: 'app-text-editor',    
9
  templateUrl: './text-editor.component.html',    
10
  styleUrls: ['./text-editor.component.css']    
11
})    
12
export class TextEditorComponent implements OnInit {    
13
  name = 'ng2-ckeditor';    
14
  ckeConfig: any;    
15
   mycontent: string;    
16
  log: string   
17
  @ViewChild('PageContent') PageContent: any;    
18
  res: any;    
19
     
20
  constructor(private contentservice:ContentService,private router: Router) { }    
21
  contentdata=new Content();    
22
    
23
  ngOnInit() {    
24
    this.Getcontent()    
25
    this.ckeConfig = {    
26
      allowedContent: false,    
27
      extraPlugins: 'divarea',    
28
      forcePasteAsPlainText: true    
29
    };    
30
  }    
31
  onSubmit()    
32
  {    
33
    debugger;    
34
    debugger;    
35
    this.contentservice.AddUpdateContent(this.contentdata).subscribe((data : any) => {    
36
      debugger;    
37
      alert("Data saved Successfully");    
38
      this.router.navigate(['/Post']);    
39
    
40
    })    
41
  }    
42
  Getcontent()    
43
  {    
44
    this.contentservice.Getcontent().subscribe((data:any)=>{    
45
      this.res=data;    
46
      console.log(this.res);    
47
    })    
48
  }    
49
}    



Step 9 

Now, open pagecontent.component.html and add the following HTML:

HTML




xxxxxxxxxx
1
18


 
1
<table class="table">    
2
  <thead>    
3
    <tr>    
4
      <th scope="col">#</th>    
5
      <th scope="col">Title</th>    
6
      <th scope="col">Content</th>    
7
       <th scope="col">Details</th>    
8
    </tr>    
9
  </thead>    
10
  <tbody>    
11
    <tr *ngFor="let data of res">    
12
      <th scope="row">{{data.Id}}</th>    
13
      <td>{{data.Title}}</td>    
14
      <td>{{data.Content}}</td>    
15
      <td>  <button (click)="GetcontentById(data.Id)" type="submit" class="btn btn-info">Details</button></td>     
16
    </tr>    
17
  </tbody>    
18
</table>   


 

Open the pagecontent.componet.ts file and add the following lines:

TypeScript




xxxxxxxxxx
1
33


 
1
import { Component, OnInit } from '@angular/core';  
2
import { ContentService } from "../content.service";   
3
import { Router } from '@angular/router';  
4
@Component({  
5
  selector: 'app-pagecontent',  
6
  templateUrl: './pagecontent.component.html',  
7
  styleUrls: ['./pagecontent.component.css']  
8
})  
9
export class PagecontentComponent implements OnInit {  
10
  res: any;  
11
  terms: any;  
12
  cont: any;  
13
  
14
  constructor(private contentservice:ContentService,private router: Router) { }  
15
  
16
  ngOnInit() {  
17
   this.Getcontent()  
18
  }  
19
  Getcontent()  
20
  {  
21
    this.contentservice.Getcontent().subscribe((data:any)=>{  
22
      this.res=data;  
23
      this.terms= this.res[1].pageContentTitle;  
24
      this.cont= this.res[1].Content;  
25
      console.log(this.res);  
26
    })  
27
  }  
28
  GetcontentById(id:number)  
29
  {  
30
    this.router.navigate(['/Details'], { queryParams: { Id: id } });  
31
  }  
32
  
33
}  



Step 10

Now, open detailspost.component.html and add the following HTML:

HTML




xxxxxxxxxx
1


 
1
<div>    
2
        <div>                   
3
            <h5 style="color:orange;text-align: center">{{this.Title}}</h5>    
4
            <hr style="color: blue;">    
5
              <span>     
6
              <div style="color:#788594" [innerHTML]="this.content"></div>    
7
              </span>     
8
        </div>    
9
    </div>    



Open detailspost.componet.ts file and add the following lines:

TypeScript




xxxxxxxxxx
1
30


 
1
import { Component, OnInit } from '@angular/core';  
2
import { Router, ActivatedRoute, Params } from '@angular/router';  
3
import { ContentService } from '../content.service';  
4
  
5
@Component({  
6
  selector: 'app-detailspost',  
7
  templateUrl: './detailspost.component.html',  
8
  styleUrls: ['./detailspost.component.css']  
9
})  
10
export class DetailspostComponent implements OnInit {  
11
  res: any;  
12
  Title: any;  
13
  content: any;  
14
  
15
  constructor( private route: ActivatedRoute,private contentservice:ContentService) { }  
16
  
17
  ngOnInit() {  
18
    let Id = this.route.snapshot.queryParams["Id"]  
19
   this.GetcontentById(Id);  
20
  }  
21
  GetcontentById(Id:string)  
22
  {  
23
     this.contentservice.GetcontentById(Id).subscribe((data: any)=>{  
24
       this.res=data;  
25
       this.Title=this.res.Title  
26
       this.content=this.res.Content  
27
       console.log(this.res);  
28
    });  
29
  }  
30
}  



Step 11

Now, open the app-routing.module.ts file and add the following lines to create routing:

TypeScript




xxxxxxxxxx
1
18


 
1
import { NgModule } from '@angular/core';  
2
import { Routes, RouterModule } from '@angular/router';  
3
import { PagecontentComponent } from './pagecontent/pagecontent.component';  
4
import { TextEditorComponent } from './text-editor/text-editor.component';  
5
import { DetailspostComponent } from './detailspost/detailspost.component';  
6
  
7
const routes: Routes = [  
8
  { path: '', component: TextEditorComponent },  
9
  { path: 'Post', component: PagecontentComponent },  
10
  { path: 'Details', component: DetailspostComponent }  
11
  
12
  
13
]  
14
@NgModule({  
15
  imports: [RouterModule.forRoot(routes)],  
16
  exports: [RouterModule]  
17
})  
18
export class AppRoutingModule { }  



Step 12 — Create a new Web API Project

Open Visual Studio and create a new project. 

Creating a new project in VS Code 

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. 

C#




xxxxxxxxxx
1


 
1
public class Response    
2
   {    
3
       public string Status { get; set; }    
4
       public string Message { get; set; }    
5
   } 


   

Right-click the Controllers folder and add a new controller. Name it "Content controller" and add the following namespace in the Content controller.

C#




x



1
using TextEditor.Models;  



Now, add a method to insert and update data into the database.

Step 14 - Complete Content Controller Code 

C#




xxxxxxxxxx
1
55


 
1
using System;  
2
using System.Collections.Generic;  
3
using System.Linq;  
4
using System.Net;  
5
using System.Net.Http;  
6
using System.Web.Http;  
7
using TextEditor.Models;  
8
  
9
namespace TextEditor.Controllers  
10
{  
11
    public class ContentsController : ApiController  
12
    {  
13
        [HttpPost]  
14
        public object saveconetnt(Content Con)  
15
        {  
16
            try  
17
            {  
18
                dbCoreEntities2 db = new dbCoreEntities2();  
19
                Post Em = new Post();  
20
                if (Em.Id == 0)  
21
                {  
22
                    Em.Content = Con.PageContent;  
23
                    Em.Title =Con.PageContentTitle ;  
24
                    db.Posts.Add(Em);  
25
                    db.SaveChanges();  
26
                    return new Response  
27
                    { Status = "Success", Message = "SuccessFully Saved." };  
28
                }  
29
            }  
30
            catch (Exception ex)  
31
            {  
32
  
33
                throw;  
34
            }  
35
            return new Response  
36
            { Status = "Error", Message = "Invalid Data." };  
37
        }  
38
       [Route("Api/Contents/Getpagdata")]  
39
        [HttpGet]  
40
        public object Getpagecontent()  
41
        {  
42
            dbCoreEntities2 db = new dbCoreEntities2();  
43
            return db.Posts.ToList();  
44
        }  
45
        //[Route("Api/Login/")]  
46
        [HttpGet]  
47
        public object GetpagecontentById(int id)  
48
        {  
49
            dbCoreEntities2 db = new dbCoreEntities2();  
50
            var obj = db.Posts.Where(x => x.Id == id).ToList().FirstOrDefault();  
51
            return obj;  
52
        }  
53
    }  
54
  
55
}    



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:

C#




xxxxxxxxxx
1


 
1
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");      
2
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

  • How to Develop a RESTful Web Service in ASP.NET Web API.
  • Angular Essentials.
  • Angular Tutorial: Angular 7 and the RESTEasy Framework.
Text editor AngularJS application TypeScript Web API Visual Studio Code

Opinions expressed by DZone contributors are their own.

Trending

  • File Upload Security and Malware Protection
  • Tactics and Strategies on Software Development: How To Reach Successful Software [Video]
  • Constructing Real-Time Analytics: Fundamental Components and Architectural Framework — Part 2
  • 10 Traits That Separate the Best Devs From the Crowd

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: