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 use 'ng2-ckeditor' editor. Learn more about
Cheditor.
Prerequisites
- Basic Knowledge of Angular 2 or higher
- Visual Studio Code
- Visual Studio and SQL Server Management studio
- Node and NPM installed
- Bootstrap
Step 1
Create an Angular project by using the following command.
Step 2
Open this project in Visual Studio Code and install bootstrap by using the following command:
- npm install bootstrap --save
Now open styles.css file and add Bootstrap file reference. To add a reference in styles.css file, add this line:
- @import '~bootstrap/dist/css/bootstrap.min.css';
Step 3
Now install ng2-ckeditor library in this project, to install ng2-ckeditor library use the following command:
Now add CKEditor javascript reference in index.html file,open Index.html file and the following line:
- <script src="https://cdn.ckeditor.com/4.9.2/full-all/ckeditor.js"></script>
Step 4
Now include CKEditorModule in app.module.ts file
- 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:
Now add the following line Content.service.ts file:
- 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" by using the following command and add the following lines:
- export class Content {
- Id:number;
- Title:string;
- Content:string;
- }
Step 7
Now let's create 3 new components by using the following commands:
- Texteditor
- Pagecontent
- detailspost
- ng g c Texteditor
- ng g c pagecontent
- ng g c detailspost
Step 8
Now, open texteditor.component.html and add the following HTML code to design the registration form:
- <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 texteditor.componet.ts file and add the following lines:
- 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:
- <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 pagecontent.componet.ts file and add the following lines:
- 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:
- <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:
- 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 app-routing.module.ts file and add the following lines to create
routing:
- 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.
Step 13
Change the name to Texteditor.
Step 14
Choose the template as Web API.
Step 15
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
Step 16
Click on the "ADO.NET Entity Data Model" option and click "Add".
Step 17
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.
Step 18
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 19
Right-click on the Models folder and add a class Response. Now, paste the following code in these classes.
- public class Response
- {
- public string Status { get; set; }
- public string Message { get; set; }
- }
Right-click on the Controllers folder and add a new controller. Name it as "Content controller" and add the following namespace in the Content controller.
Now, add a method to insert and update data into the database.
Step 20 - Complete Content controller code
- 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();
- }
-
- [HttpGet]
- public object GetpagecontentById(int id)
- {
- dbCoreEntities2 db = new dbCoreEntities2();
- var obj = db.Posts.Where(x => x.Id == id).ToList().FirstOrDefault();
- return obj;
- }
- }
-
- }
Step 21
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 Webapiconfig.cs and add the following lines:
- EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
- config.EnableCors(cors);
Step 22
Now, go to visual studio code and run the project by using the following command: 'npm start'
Enter some values, add styles to text in text editor and click on the submit button.
Click on the details button and check.
Summary
In this article, we learned how we integrate a text editor in an Angular application.