The text editor is a program for adding and editing text. In this post, we will learn how to add a text editor in an Angular 8 application.
Prerequisites
Create an Angular project by using the following command.
ng new TextEditor
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';
Now install ng2-ckeditor library in this project, to install ng2-ckeditor library use the following command:
npm install ng2-ckeditor
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>
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 { }
Now create a service to call the Web API by using the following command:
ng g s Content
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);
}
}
Create a class named “Content” by using the following command and add the following lines:
export class Content {
Id:number;
Title:string;
Content:string;
}
Now let’s create 3 new components by using the following commands:
ng g c Texteditor
ng g c pagecontent
ng g c detailspost
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);
})
}
}
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 } });
}
}
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);
});
}
}
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 { }
Create a new Web API project
Open Visual Studio and create a new project.
Change the name to Texteditor.
Choose the template as Web API.
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.
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.
using TextEditor.Models;
Now, add a method to insert and update data into the database.
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();
}
//[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;
}
}
}
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);
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.
Thank for reading. Did you find this information helpful?
#Angular #Angular 8 #Asp.net #Web API #SQL Server