Angular 6 convert string to an Html using pipe - javascript

My input string is
html:string="<a role="button" class=" fas fa-trash-alt fa-1x" title="Remove Link" href="#"></a>"
I want this to be converted into an raw html
Pipe:
import { Pipe, PipeTransform } from '#angular/core';
import { DomSanitizer } from '#angular/platform-browser'
#Pipe({
name: 'htmldecoder'
})
export class HtmldecoderPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) { }
transform(value) {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
Html Code :
<div>
<div [innerHtml]="html | htmldecoder">
</div>
</div>
The output getting in UI is
<a role="button" class="fas fa-trash-alt fa-1x" title="Remove Link" href="#"></a>
Expected Output Should be the Button

Make this following changes in your code and it will work, the code quite simple for self-explanation
app.component.ts
html = `html:string="<a role="button" class=" fas fa-trash-alt fa-1x" title="Remove Link" href="#">aditya</a>"`;
pipe
transform(value) {
value = value.substring(13, value.length-1);
var doc = new DOMParser().parseFromString(value, "text/html");
const value123 = doc.documentElement.textContent;
return this.sanitized.bypassSecurityTrustHtml(value123);
}
app.component.html
<div [innerHTML]="html | htmldecoder">

Related

Create Custom Social Share Buttons in angular

I will appreciate any ideas and support for this issue
I have an angular project and I try to create icons share buttons for social media.
I have a component named landing.component. in the HTML file I implemented a Modal popup to allow showing a new windows where I have the icons. Please, follow screenshots below
Below, is the new windows
the HTML code is here
<div class="card-wrapper" fxLayout="row wrap" fxLayoutAlign="start start">
<div
class="card active-card"
fxFlex="25"
*ngFor="let category of categories"
(click)="categoryClick(category)"
>
<picture>
<img [src]="category.imageLocation" />
</picture>
<div class="card-overlay" fxLayout="row wrap" fxLayoutAlign="center end">
<span class="card-title" fxFlex="100">{{ category.title }}</span>
<div class="card-buttons" fxFlex="100" fxLayout="row">
<ul class="list-inline text-center member-icons ">
<li class="list-inline-item">
<button mat-icon-button disableRipple class="btn btn-primary" routerLink="/mtl" (click)="open(content)"><i class="fa-solid fa-share"></i></button>
</li>
<span fxFlex></span>
</ul>
<!-- <button mat-icon-button disableRipple>
<heart-icon></heart-icon>
</button> -->
<!-- <span fxFlex></span> -->
<!-- <button mat-icon-button disableRipple> -->
<!-- <download-icon></download-icon> -->
<!-- </button> -->
<!-- <button mat-icon-button disableRipple>
<share-icon></share-icon>
</button> -->
</div>
</div>
</div>
</div>
<section
class="cragcity-container p-t-5"
fxLayout="row"
fxLayoutAlign="space-between start"
>
<div style="margin: auto">
<img class="socmed-icon m-r-15" src="./assets/icons/facebook.webp" />
<img class="socmed-icon m-r-15" src="./assets/icons/skype.webp" />
<img class="socmed-icon" src="./assets/icons/instagram.webp" />
</div>
</section>
<ng-template #content let-modal>
<div class="modal-header">
<h4 class="modal-title" id="modal-basic-title">Share Social Media</h4>
<button type="button" class="btn-close" aria-label="Close" (click)="modal.dismiss('Cross click')"></button>
</div>
<div class="modal-body">
<form>
<div class="mb-3">
<label for="Social Media"></label>
<div class="share-btn-container">
<a #facebook href="#" class="facebook-btn">
<i class="fab fa-facebook"></i>
</a>
<a href="#" class="twitter-btn">
<i class="fab fa-twitter"></i>
</a>
<a href="#" class="pinterest-btn">
<i class="fab fa-pinterest"></i>
</a>
<a href="#" class="linkedin-btn">
<i class="fab fa-linkedin"></i>
</a>
<a href="#" class="whatsapp-btn">
<i class="fab fa-whatsapp"></i>
</a>
</div>
<!-- <div class="input-group">
<input
name="dp"
ngbDatepicker
#dp="ngbDatepicker"
/>
<button class="btn btn-outline-secondary bi bi-calendar3" (click)="dp.toggle()" type="button"></button>
</div> -->
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark" (click)="modal.close('Save click')">Close</button>
</div>
</ng-template>
<app-cragcity-footer></app-cragcity-footer>
In the facebook option, I created a variable #facebook that will allow me to use viewchildren in the ts file to do an elementref and find the element in the DOM.
In the viewchildren option, I created a variable link1.
then, in the ngAfterViewInit I created two variables url and title. the url variable will take the link of my page to be share and the title is just message.
Finally, I used this command:
this.link1.nativeElement.setAttribute("href",`https://www.facebook.com/sharer.php?u=${this.url}`)
(this is what I believe is the same in js document.location.href) but used in ts
The code is not working, basically when I click the facebook icon only close the windows and that's it and the web shows me this error here bbelwo:
the landing. component.ts code is here below:
import { Component, OnInit, Input, ViewChild, ElementRef, AfterViewInit, ViewChildren } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { DataService } from 'src/app/core/services/data.service';
import { category } from '../models/category';
import { ModalDismissReasons, NgbActiveModal, NgbModal } from '#ng-bootstrap/ng-bootstrap';
#Component({
selector: 'app-landing',
templateUrl: './landing.component.html',
styleUrls: ['./landing.component.scss']
})
export class LandingComponent implements OnInit, AfterViewInit {
public categories = new Array<category>();
#Input() name;
url:string;
title:string;
closeResult: string | undefined;
constructor(private _dataService: DataService, private router: Router, private modalService: NgbModal, private route: ActivatedRoute) {
}
ngOnInit(): void {
this.retrieveCategories();
}
#ViewChildren("facebook")link1: ElementRef;
ngAfterViewInit() {
this.url = this.router.url;
/* this.link1.nativeElement = this.url; */
this.title = encodeURI("Facebook");
this.link1.nativeElement.setAttribute("href",`https://www.facebook.com/sharer.php?u=${this.url}`)
/* console.log(this.link1);
console.log(this.url);
*/
/* this.link1.nativeElement.setAttribute('xlink:href') */
}
retrieveCategories() {
const actionUrl = 'v1/category';
const params = {};
this._dataService.get<any>(actionUrl, params)
.subscribe(data => {
if (data !== null) {
if (!data.isError) { this.categories = data.result; }
}
});
}
categoryClick(data: category) {
if (data.subCategory.length > 0)
this.router.navigate(['mtl', data.id]);
}
open(content) {
this.modalService.open(content, { ariaLabelledBy: 'modal-basic-title' }).result.then(
(result) => {
this.closeResult = `Closed with: ${result}`;
},
(reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
},
);
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
}
I really appreciate any help
Regards
First it is a different between #ViewChild and #ViewChildren. The first will search one element, the second multiple elements. So in your case use #ViewChild("facebook") link1: any;
But a besser approach is to let Angular do this thing and don't use setAttribute to the native element. So you can bind anything to the href attribute like this:
HTML
<a #facebook [href]="facebookLink" class="facebook-btn">
<i class="fab fa-facebook"></i>
</a>
Code
facebookLink: string = "https://facebook.com";
You can generate the links with a ngFor loop, too for more flexibility.
CODE
linkObjects = [{iconClassI: "fab fa-facebook", iconClassA: "facebook-btn", link: "http://facebook.com"}, {... all other links}]
HTML
<div class="share-btn-container">
<a *ngFor="let item of linkObjects" [href]="item.link" [class]="item.iconClassA">
<i [class]="item.iconClassI"></i>
</a>
</div>

Need dynamically created buttons to work independently in Angular

In Angular i have dynamically created a group of buttons that all have the same action (to show text when clicked) everything works fine yet when I click one button they all perform the action. I need them to work independently of each other. I have dynamically made a different id for each button and was wondering if there was a way to us the id to have them work independently.
Button HTML and TS files:
<button id="{{index}}" class="btn btn-secondary" style="float: right;" (click)="onClick()">Discription</button>
import { Component, EventEmitter, OnInit, Output, Input } from '#angular/core';
#Component({
selector: 'app-discription-btn',
templateUrl: './discription-btn.component.html',
styleUrls: ['./discription-btn.component.css']
})
export class DiscriptionBtnComponent implements OnInit {
#Output() btnClick = new EventEmitter();
#Input() index!: number
constructor() { }
ngOnInit(): void { }
onClick() {
this.btnClick.emit();
}
}
Button Parent HTML and TS files:
<div class="card mb-4 h-100">
<img class="card-img-top-other" src= "{{ post.link }}" />
<div class="card-body">
<div class="small text-muted"> {{ post.created }} <app-discription-btn (btnClick) = "toggleDiscription()" [index] = index></app-discription-btn> </div>
<h2 class="card-title h4"> {{ post.title }} </h2>
<div *ngIf="showDiscription">
<p class="card-text"> {{ post.summary }} </p>
<a class="btn btn-primary" href="#!">Read More -></a>
</div>
</div>
</div>
import { Component, OnInit, Input } from '#angular/core';
import { Subscription } from 'rxjs';
import { BlogPost } from 'src/app/Post';
import { DiscriptionUiService } from 'src/app/services/discription-ui.service';
#Component({
selector: 'app-other-posts',
templateUrl: './other-posts.component.html',
styleUrls: ['./other-posts.component.css']
})
export class OtherPostsComponent implements OnInit {
#Input() post! : BlogPost
#Input() index! : number;
showDiscription : boolean = false;
subscription : Subscription;
constructor(private discritpionService: DiscriptionUiService) {
this.subscription = this.discritpionService.onToggle().subscribe((value) => (this.showDiscription = value));
}
ngOnInit(): void {
}
toggleDiscription(){
this.discritpionService.toggleDiscription();
}
}
Main HTML and TS files:
<div class="container">
<div class="row">
<div class="col-lg-8"><app-featured-post *ngFor="let post of posts; let i = index;" [post] = "post" [index] = "i"></app-featured-post></div>
<div class="col-lg-4"><app-side-widgets></app-side-widgets></div>
<app-other-posts *ngFor="let post of posts | myFilterPipe:filterargs; let i = index;" [post] = "post" [index] = "i" class="col-lg-4" style="padding-top: 10px;" ></app-other-posts>
<nav aria-label="Pagination">
<hr class="my-0" />
<ul class="pagination justify-content-center my-4">
<li class="page-item disabled"><a class="page-link" href="#" tabindex="-1" aria-disabled="true">Newer</a></li>
<li class="page-item active" aria-current="page"><a class="page-link" href="#!">1</a></li>
<li class="page-item"><a class="page-link" href="#!">Older</a></li>
</ul>
</nav>
</div>
</div>
import { Component, OnInit } from '#angular/core';
import { BlogPostService } from 'src/app/services/blog-post.service';
import { BlogPost } from '../../Post';
#Component({
selector: 'app-posts',
templateUrl: './posts.component.html',
styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {
filterargs = {title: 'The Beginning'}
posts: BlogPost[] = [];
constructor(private postService: BlogPostService ) { }
ngOnInit(): void {
this.postService.getPosts().subscribe((posts) => (this.posts = posts));
}
}
Any ideas would be a great help. Thank you ahead of time!

Angular 6 : display comments under section commented

I have crud app , which user can add comments , I want comments to be displayed under each section commented, now all added comments displays below all section.
here is components ts
import { Component, OnInit } from '#angular/core';
import { Task } from '../model/task.model';
import { Comment } from '../model/comment.model';
import { Router } from '#angular/router';
import { UserService } from '../service/user.service';
import {first} from 'rxjs/operators';
import {FormBuilder, FormGroup, Validators} from '#angular/forms';
import { ActivatedRoute } from '#angular/router';
#Component({
selector: 'app-task-list',
templateUrl: './task-list.component.html',
styleUrls: ['./task-list.component.scss']
})
export class TaskListComponent implements OnInit {
tasks: Task[];
comments: Comment[];
// tslint:disable-next-line:max-line-length
constructor(private formBuilder: FormBuilder, private router: Router, private activeRouter: ActivatedRoute, private userService: UserService) { }
addForm: FormGroup;
ngOnInit() {
this.userService.getTask()
.subscribe( data => {
this.tasks = data;
});
this.activeRouter.params.subscribe((params) => {
// tslint:disable-next-line:prefer-const
let id = params['id'];
this.userService.getComments(id)
.subscribe(data => {
this.comments = data;
});
});
this.addForm = this.formBuilder.group({
id: [],
author: ['', Validators.required],
description: ['', Validators.required],
});
}
addComments(task_id) {
const formData = this.addForm.value;
formData.task_id = task_id;
this.userService.addComments(formData)
.subscribe(data => {
this.comments.push(this.addForm.value);
});
this.router.navigate(['task-list']);
}
}
Here is task list html i have
<div class="container task-list">
<div class="row">
<div class="col-sm-8">
<div class="panel panel-white post panel-shadow" *ngFor="let task of tasks">
<div class="post-heading">
<div class="pull-left meta">
<div class="title h4">
<b>{{task.title}}</b>
</div>
<h6 class="text-muted time">1 minute ago</h6>
</div>
</div>
<div class="post-description">
<p>{{task.description}}</p>
<div class="stats">
<a href="#" class="btn btn-default stat-item">
<i class="fa fa-thumbs-up icon"></i>2
</a>
<a href="#" class="btn btn-default stat-item">
<i class="fa fa-thumbs-down icon"></i>12
</a>
</div>
</div>
<form class="post-form" [formGroup]="addForm" (ngSubmit)="addComments(task.id)">
<div class="form-group task-group">
<div class="form-group">
<label class="">Author</label>
<input type="text" class="form-control" formControlName="author" id="author" />
</div>
<div class="form-group">
<label class="">Comments</label>
<textarea class="form-control task-textarea" rows="1" formControlName="description" id="description" ></textarea>
</div>
</div>
<button class="btn btn-default btn-submit">Submit</button>
</form>
</div>
</div>
<div class="col-sm-8">
<div class="panel panel-white post panel-shadow" *ngFor="let comment of comments">
<div class="post-heading">
<div class="pull-left image">
<img src="http://bootdey.com/img/Content/user_1.jpg" class="img-circle avatar" alt="user profile image">
</div>
<div class="pull-left meta">
<div class="title h5">
<b>{{comment.author}}</b>
made a post.
</div>
<h6 class="text-muted time">1 minute ago</h6>
</div>
</div>
<div class="post-description">
<p>{{comment.description}}</p>
<div class="stats">
<a href="#" class="btn btn-default stat-item">
<i class="fa fa-thumbs-up icon"></i>2
</a>
<a href="#" class="btn btn-default stat-item">
<i class="fa fa-thumbs-down icon"></i>12
</a>
</div>
</div>
</div>
</div>
</div>
</div>
Here is services for getting task and comments
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { User } from '../model/user.model';
import { Task } from '../model/task.model';
import { Comment } from '../model/comment.model';
#Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private http: HttpClient) { }
baseUrl = 'http://localhost:3000/users';
taskUrl = 'http://localhost:3000/task';
commentsUrl = 'http://localhost:3000/comment';
getUsers() {
return this.http.get<User[]>(this.baseUrl);
}
getUserById(id: number) {
return this.http.get<User>(this.baseUrl + '/' + id);
}
createUser(user: User) {
return this.http.post(this.baseUrl, user);
}
updateUser(user: User) {
return this.http.put(this.baseUrl + '/' + user.id, user);
}
deleteUser(id: number) {
return this.http.delete(this.baseUrl + '/' + id);
}
createTask(task: Task) {
return this.http.post(this.taskUrl, task);
}
getTask() {
return this.http.get<Task[]>(this.taskUrl);
}
addComments(comment: Comment) {
return this.http.post(this.commentsUrl, comment);
}
getComments(id: number) {
return this.http.get<Comment[]>(this.commentsUrl);
}
/*
getComments(id: number) {
return this.http.get<Comment[]>(this.commentsUrl + id);
}
*/
}
Problem: when I add comments in a certain task , displays beloww all task I have ,
Here is image how it look after adding comment
Here is what I want
What do I need to change in my code to get what I want? thanks

search results in the text box with cross symbol

update1:
hey thanks for your reply...but when I type h it shows set of values....and when I select the value it should show in the text box with cross symbol....like in stackoverflow we edit tags
I have a search engine code in angular2.
When I select the search results I need to display the values in the text box With cross button next to it.
Right now I am getting the results.
But when I slect the values, how to display in the text box with cross symbol.
https://stackblitz.com/edit/angular6-ya3e4u?file=app/app.component.html
service
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
#Injectable()
export class SearchService {
baseUrl: string = 'https://api.cdnjs.com/libraries';
queryUrl: string = '?search=';
constructor(private http: Http) { }
search(terms: Observable<string>) {
return terms.debounceTime(400)
.distinctUntilChanged()
.switchMap(term => this.searchEntries(term));
}
searchEntries(term) {
return this.http
.get(this.baseUrl + this.queryUrl + term)
.map(res => res.json());
}
}
html
<input
(keyup)="searchTerm$.next($event.target.value)">
<ul *ngIf="results">
<li *ngFor="let result of results | slice:0:9">
<a href="{{ result.latest }}" target="_blank">
{{ result.name }}
</a>
</li>
</ul>
<div class="close" (click)="delete(currentItem)">X</div>
Try the following code it will help you. Demo StackBlitz
<input
(keyup)="searchTerm$.next($event.target.value)">
<ul *ngIf="results">
<li *ngFor="let result of results | slice:0:9">
<a href="{{ result.latest }}" target="_blank">
{{ result.name }}
</a>
<div class="close rigth" (click)="delete(result)">X</div>
</li>
</ul>

Angular2 - pass dynamically loaded parameters to function while doing dropdown value selection

Please check that, I am passing the parameters of li tag click function of updateId method in the correct format or not ? The errors in the console shows that line only....
My app.component.html code is
<div class='form-group' style="width: 100%;">
<div class="btn-group" style="width: 100%;">
<button type="button" class="btn btn-default" style="width : 75%;text-align: left;">{{name}}</button>
<button type="button" data-toggle="dropdown" class="btn btn-default dropdown-toggle"><span class="caret"></span></button>
<ul class="dropdown-menu" style="width: 75%;">
<li *ngFor="let result of jsonList" ><a class="dropdown-item" (click)="updateId('{{result.id}}', '{{result.name}}')" >{{result.name}}</a>
</li>
</ul>
</div>
</div>
My app.component.ts is ,
import { HomeService } from '../../services/home.service';
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-home-component',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
id: string;
name : string;
jsonList : any;
constructor(private homeservice: HomeService) { }
ngOnInit() {
this.id = null;
this.name = "SELECT";
this.jsonList= [{"Id" : "F1", "name" : "FONE"}, {"id" : "F2", "name" : "FTWO"}]
}
updateId(id : string, name : string) : void {
this.id = id;
this.name = name;
}
}
It is not working. The error is on the li tag click function method passing the dynamic parameters from the jsonList. So pls help me to get resolve.
Don't use the handlebars {{ }} in event bindings such as the (click) attribute - they will be evaluated against the Component instance automatically. and the single quotes are not needed either. Use it like so:
<li *ngFor="let result of jsonList">
<a (click)="updateId(result.id, result.name)">{{result.name}}</a>
</li>
You don't need {{ }} while specifying arguments to an event handlers (ng-click). The correct syntax would be
<li *ngFor="let result of jsonList">
<a (click)="updateId(result.id, result.name)">{{result.name}}</a>
</li>

Categories

Resources