Вступление
В этой статье мы узнаем, как добавить текстовый редактор в приложение Angular 8. Текстовый редактор — это программа для добавления и редактирования текста. В этой демонстрации мы будем использовать редактор ng2-ckeditor . Узнайте больше о Cheditor с их официальными документами .
Предпосылки
- Базовые знания Angular 2 или выше.
- Visual Studio Code.
- Студия управления SQL Server.
- Узел и NPM установлены.
- Bootstrap.
Шаг 1
Создайте проект Angular с помощью следующей команды:
Машинопись
1
ng new TextEditor
Шаг 2
Откройте этот проект в Visual Studio Code и установите Bootstrap с помощью следующей команды:
Машинопись
xxxxxxxxxx
1
npm install bootstrap --save
Теперь откройте файл styles.css и добавьте ссылку на файл Bootstrap. Чтобы добавить ссылку в файл styles.css , добавьте эту строку:
Машинопись
xxxxxxxxxx
1
@import '~bootstrap/dist/css/bootstrap.min.css';
Вам также может понравиться:
Angular: все, что вам нужно знать [Учебники] .
Шаг 3
Теперь установите библиотеку ng2-ckeditor в этом проекте. Чтобы установить библиотеку ng2-ckeditor, используйте следующую команду:
Машинопись
xxxxxxxxxx
1
npm install ng2-ckeditor
Теперь добавьте ссылку CKEditor JavaScript в файл index.html , открыв файл index.html и добавив следующую строку:
Машинопись
xxxxxxxxxx
1
<script src="https://cdn.ckeditor.com/4.9.2/full-all/ckeditor.js"></script>
Шаг 4
Теперь, включают CKEditorModule
в app.module.ts файле.
Машинопись
xxxxxxxxxx
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 { }
Шаг 5
Теперь создайте сервис для вызова Web API с помощью следующей команды:
Оболочка
1
ng g s Content
Теперь добавьте следующую строку в файл Content.service.ts :
Машинопись
xxxxxxxxxx
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
}
Шаг 6
Создайте класс с именем «Content» со следующим кодом:
Машинопись
xxxxxxxxxx
1
export class Content {
2
Id:number;
3
Title:string;
4
Content:string;
5
}
Шаг 7
Теперь давайте создадим три новых компонента, используя следующие команды:
Texteditor
,Pagecontent
,detailspost
,
Оболочка
xxxxxxxxxx
1
ng g c Texteditor
2
ng g c pagecontent
3
ng g c detailspost
Шаг 8
Теперь откройте файл texteditor.component.html и добавьте следующий HTML-код для оформления формы регистрации:
Джава
xxxxxxxxxx
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>
Откройте файл texteditor.componet.ts и добавьте следующие строки:
Машинопись
xxxxxxxxxx
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
}
Шаг 9
Теперь откройте страницу pagecontent.component.html и добавьте следующий HTML- код :
HTML
xxxxxxxxxx
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>
Откройте файл pagecontent.componet.ts и добавьте следующие строки:
Машинопись
xxxxxxxxxx
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
}
Шаг 10
Теперь откройте файл detailspost.component.html и добавьте следующий HTML- код :
HTML
xxxxxxxxxx
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>
Откройте файл detailspost.componet.ts и добавьте следующие строки:
Машинопись
xxxxxxxxxx
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
}
Шаг 11
Теперь откройте файл app-routing.module.ts и добавьте следующие строки для создания маршрутизации :
Машинопись
xxxxxxxxxx
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 { }
Шаг 12. Создание нового проекта веб-API.
Откройте Visual Studio и создайте новый проект.
Измените имя на Texteditor .
Выберите веб-API в качестве шаблона.
Щелкните правой кнопкой мыши папку « Модели » в обозревателе решений и выберите « Добавить» >> «Новый элемент» >> «Данные» .
Выберите параметр « Модель данных объекта ADO.NET» и нажмите « Добавить» .
Выберите EF Designer из базы данных, нажмите кнопку « Далее» и добавьте свойства подключения. Выберите имя базы данных на следующей странице и нажмите OK .
Проверьте флажок таблицы . Внутренние параметры будут выбраны по умолчанию. Теперь нажмите на кнопку Готово .
Наша модель данных создана сейчас.
Шаг 13
Щелкните правой кнопкой мыши папку « Модели » и добавьте класс Response
. Теперь вставьте следующий код в класс.
C #
xxxxxxxxxx
1
public class Response
2
{
3
public string Status { get; set; }
4
public string Message { get; set; }
5
}
Щелкните правой кнопкой мыши папку « Контроллеры » и добавьте новый контроллер. Назовите его «Контроллер контента» и добавьте следующее пространство имен в Контроллер контента.
C #
x
1
using TextEditor.Models;
Теперь добавьте метод для вставки и обновления данных в базу данных.
Шаг 14 — Полный код контроллера контента
C #
xxxxxxxxxx
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
}
Шаг 15
Теперь давайте включим CORS. Перейдите в Инструменты , откройте диспетчер пакетов NuGet , найдите CORS и установите пакет Microsoft.Asp.Net.WebApi.Cors . Откройте файл Webapiconfig.cs и добавьте следующие строки:
C #
xxxxxxxxxx
1
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
2
config.EnableCors(cors);
Шаг 16
Теперь перейдите в Visual Studio кодекса и запустить проект, используя следующую команду: npm start
.
Введите несколько значений, добавить стили к тексту, и нажмите на представить кнопку.
Нажмите на кнопку детали и проверьте вывод. Вы должны иметь что-то вроде следующего изображения.
Резюме
В этой статье мы узнали, как интегрировать текстовый редактор в приложение Angular.