search results in the text box with cross symbol - javascript

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>

Related

How to work with variables from a loop in HTML and with a component property?

The data I work with (bosses[]) has a boss object with contains the key-value email which is an string. I want to create the anchor with that string in the HTML. Also note that there's a loop in HTML that allows to access to each boss in bosses[].
So how can I access to create an anchor with boss.email which it only exists in the HTML loop?
I've tried <a [href]=`"mailto: + boss.email"></a> but doesn't work.
the html:
<div class="boss" *ngFor="let boss of bosses" >
<div class="boss-text">
<div class="boss-text-name">{{boss.name}} </div>
<div>{{boss.email}}</div>
<a [href]="mailto: + boss.email"></a>
</div>
</div>
The component:
import { Component, Input, OnInit } from '#angular/core';
import { boss} from 'interfaces'
#Component({
templateUrl: 'boss-cell.component.html',
selector: 'boss-cell',
})
export class BossCellComponent implements OnInit {
constructor() {}
bosses: any[] = [{
email: 'kennedy#gmail.com',
name: 'kennedy',
}]
}
You're close! I think this is what you're looking for:
<div class="boss" *ngFor="let boss of bosses" >
<div class="boss-text">
<div class="boss-text-name">{{boss.name}} </div>
<a [href]="'mailto:' + boss.email">{{ boss.email }}</a>
</div>
</div>
You can use interpolation as Suraj already mentionned in the comments, or bind to a function creating the string. Depending on weather you are going to link other elements to the mail, you should pick the cleanest option for you.
Template
<div class="boss" *ngFor="let boss of bosses; let i = index">
<div class="boss-text">
<div class="boss-text-name">{{ boss.name }}</div>
<a [href]="getMail(i)">{{ boss.email }}</a>
</div>
</div>
Script
bosses: any[] = [{
email: 'kennedy#gmail.com',
name: 'kennedy',
}]
getMail(index: number) {
return 'mailto:' + this.bosses[index].email
}
You need to update this line
<a [href]="'mailto:' + boss.email">{{ boss.email }}</a>

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!

pipe fail on gallery search

Hi I've done this filter pipe where I want to look for my imagename and my imageid from all my images, but it just looks for the name and id from the first image.
Anything is wrong on my code aparently.
This is my filter.pipe.ts class where I implement my search method
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(value: any, arg: any): any {
if (arg === '' || arg.length < 1) return value;
const resultPosts = [];
for (const imagen of value) {
if (imagen.name.toLowerCase().indexOf(arg.toLowerCase()) > -1) {
resultPosts.push(imagen);
}else if (imagen.imagenId.toLowerCase().indexOf(arg.toLowerCase()) > -1){
resultPosts.push(imagen);
};
return resultPosts;
}
}
}
My list.component.html where I have my input for searching:
<div class="row">
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text"name="filterImagen" placeholder="Search" [(ngModel)]="filterImagen">
<button class="btn btn-primary my-2 my-sm-0" type="submit">Search</button>
</form>
<div class="col-md-4" *ngFor="let imagen of imagenes | filter:filterImagen; index as i">
//when I look for the imagename or imageid, it just looks if my first image has the name I write on the searchbar
<div class="card mb-3 animated zoomIn">
<h3 class="card-header">{{imagen.name}}</h3>
<div class="card-body">
<h5 class="card-title"><b>ID: </b>{{imagen.imagenId}}</h5>
</div>
<div class="card-body text-center">
<img style="height: 200px; width: 100%; display: block;" src="{{imagen.imagenUrl}}" alt="Card image">
</div>
</div>
</div>
</div>
/* On my list.component.ts (here I just have a variable filter declared like: )*/
imagenes: Imagen[] = [];
filterImagen = ''; //just declared it here
//I already imported my FormsModule on app.module.ts and my classes.
Did you remember to add the pipe to Declarations? Or better yet, export it from a module, and import that module into the app.module?
UPDATE - I see your error :)
You have to move return resultPosts out of the for-loop.
If you're interested, I refactored the pipe for clarity:
import { Pipe, PipeTransform } from "#angular/core";
import { Imagen } from "./app.component";
#Pipe({
name: "filter"
})
export class FilterPipe implements PipeTransform {
transform(value: Imagen[], arg: any): any {
if (arg === "" || arg.length < 1) return value;
return value.filter(imagen => imagen.name.toLowerCase().indexOf(arg.toLowerCase()) > -1 ||
imagen.imagenId.toLowerCase().indexOf(arg.toLowerCase()) > -1
);
}
}

How to verify if my list with checkbox are all checked using Angular 5

I created a list with one checkbox for each item, and I need to verify if all of them are ckecked.
This is my HTML:
<ul class="ingredient-list" >
<li class="btn-list" *ngFor="let ingredient of recipe.ingredients">
<label class="checky round">
<input type="checkbox" checked>
<span></span>
<span>{{ ingredient }}</span>
</label>
</li>
</ul>
in your component ts file
import { FormArray, FormBuilder, FormGroup, Validators, FormControl } from '#angular/forms';
ingredientsForm;
constructor( private fb: FormBuilder) { }
ngOnInit() {
//do what you need to get your recipe details first
const ingredientFGs = recipe.ingredients.map(ingredient => this.fb.group(ingredient));
ingredientFGs.forEach(item => {
item.addControl('isChecked', new FormControl());
item.get('isChecked').setValue(false);
item.get('isChecked').setValidators(Validators.requiredTrue);
})
this.ingredientsForm = this.fb.group({
ingredients: this.fb.array(ingredientFGs);
});
}
and in your html
<form [formGroup]="ingredientsForm">
<ul class="ingredient-list" formArrayName="ingredients">
<li class="btn-list" *ngFor="let ingredient of ingredients.controls">
<label class="checky round">
<input type="checkbox" formControlName="isChecked">
<span></span>
<span>{{ ingredient.value() }}</span>
</label>
</li>
</ul>
</form>
then doing ingredientsForm.valid will return true if everything is checked
As I dind'nt wanted to import others modules just for solve this problem I came up with another idea.
I created a method at my component.ts to verify the checkbox:
import { Component, ViewChild, ElementRef } from '#angular/core';
#Component({
selector: 'app-recipes',
templateUrl: './recipes.component.html',
styleUrls: ['./recipes.component.css']
})
export class RecipesComponent {
#ViewChild('ingredientList') ingredientList: ElementRef;
#ViewChild('preparationList') preparationList: ElementRef;
isAllChecked(list: ElementRef): boolean{
// take the inputs by tag and convert to array
var inputs = [].slice.call(list.nativeElement.getElementsByTagName('input'));
return !inputs.some(function(input){
// verify if any item is not checked
return input.ckecked == false;
});
}
}
My HTML looks like this now
<ul #ingredientList >
<li #item class="btn-list" *ngFor="let ingredient of recipe.ingredients">
<label class="checky round">
<input type="checkbox" >
<span></span>
<span>{{ ingredient }}</span>
</label>
</li>
</ul>
Thanks everyone for the help

Angular2 Service render HTML

Working through an Angular2 tutorial. The challenge was to create a 'tweet' component that used a 'tweet' service to retrieve its posts.
The service is to return an array of hard-coded tweets. This is just for the sake of exercise; obviously not efficiency. However, the service can only return an array of strings so I am not sure how to return an array of HTML that can then be rendered as HTML rather than text in the view. I've read up and seen that there are of course better ways of accomplishing this than through a service, perhaps through a directive. However this is what the challenge is.
This is what I've come up with so far. The view renders the array of tweets from the service as text. Everything else works fine as I tested it with the service returning an array of strings which rendered as planned.
app.component.ts:
import {Component} from 'angular2/core';
import {TweetComponent} from './tweet.component'
#Component({
selector: 'my-app',
template: `
<tweet></tweet>
`,
directives: [TweetComponent]
})
export class AppComponent {
}
tweet.component.ts:
import {Component} from 'angular2/core'
import {TweetService} from './tweet.service'
#Component ({
selector: 'tweet',
template: `
<li *ngFor="#tweet of tweets">
{{tweet}}
</li>
`,
providers: [TweetService]
})
export class TweetComponent {
tweets;
constructor(tweetService: TweetService){
this.tweets = tweetService.getTweets();
}
}
tweet.service.ts:
export class TweetService {
getTweets() {
return [`
<div class="media">
<div class="media-left">
<a href="#">
<img class="media-object" src="http://lorempixel.com/100/100/people/?1" alt="...">
</a>
</div>
<div class="media-body">
<h4 class="media-heading">Tweet 1<br>Media Title 1?<br><like></like></h4>
</div>
</div>
`,
`
<div class="media">
<div class="media-left">
<a href="#">
<img class="media-object" src="http://lorempixel.com/100/100/people/?2" alt="...">
</a>
</div>
<div class="media-body">
<h4 class="media-heading">Tweet 2<br>Media Title 2<br><like></like></h4>
</div>
</div>`
];
}
}
In tweet.component.ts use innerHTML:
import {Component} from 'angular2/core'
import {TweetService} from './tweet.service'
#Component ({
selector: 'tweet',
template: `
<li *ngFor="#tweet of tweets">
<span [innerHTML]="tweet"></span>
</li>
`,
providers: [TweetService]
})
by the way, if you are using more recent angular2 version you should change
<li *ngFor="#tweet of tweets">
to
<li *ngFor="let tweet of tweets">

Categories

Resources