when selecting input leave only it as an available option - javascript

I have an input with ngfor, it appears several options
<article *ngIf="layout=='esalpet'" class="filter-group">
<header class="card-header">
<a href="#" data-toggle="collapse" data-target="#collapse_4" aria-expanded="true" class="">
<i class="icon-control fa fa-chevron-down"></i>
<h6 class="title">Marcas</h6>
</a>
</header>
<div class="filter-content collapse show" id="collapse_4">
<div *ngFor="let categ of filtro" class="card-body">
<label class="custom-control custom-radio">
<input (change)="filterMarcas($event)" class="custom-control-input" type="radio" id="5" name="marca"
value="{{categ.marcaJ.marca}}" id="flexCheckChecked" />
<div class="custom-control-label" id="5">{{categ.marcaJ.marca}}</div>
</label>
</div>
<!-- card-body.// -->
</div>
when selecting some of the inputs, I would like only the input selected by the user to appear
follow my method i tried to do
filterMarcas(event){
this.slicedItems = this.slicedItems.filter(item => item.marcaJ?.marca === event.target.value )
console.log(this.slicedItems)
this.filtro = this.slicedItems.filter((record, index) => this.filtro.findIndex(check => check.marcaJ?.marca === record.marcaJ?.marca) === index);
this.peso = this.peso.filter((record, index) => this.peso.findIndex(check => check.peso === record.peso) === index);
}
Is there a better method than this?
this.filtro = this.slicedItems.filter((record, index) => this.filtro.findIndex(check => check.marcaJ?.marca === record.marcaJ?.marca) === index);
Can anyone help me with this ?

Create a new PipeTransform
import { Pipe, PipeTransform } from '#angular/core';
interface Marca {
marcaJ: {
marca: string
}
}
#Pipe({
name: 'marcaFilter'
})
export class MarcaFilterPipe implements PipeTransform {
transform(marcas: Marca[], name: string): Marca[] {
if (!name) {
return marcas;
}
return marcas.filter(marca => marca.marcaJ?.marca === name);
}
}
Declare it within your module.
#NgModule({
...,
declarations: [
...
MarcaFilterPipe,
],
})
export class AppModule { }
And add the pipe to your *ngFor
<div *ngFor="let categ of filtro | marcaFilter: categ.marcaJ.marca">
...
</div>

Related

I am working on exam portal using angular and spring boot, I got a problem here when i am using name as [name]

Component.html
<div class="bootstrap-wrapper" *ngIf="!isSubmit">
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
<!-- instructions -->
<h2>Instructions</h2>
</div>
<div class="col-md-8">
<!-- questions -->
<ng-container *ngIf="questions">
<h2>{{questions[0].quiz.title}}</h2>
</ng-container>
<mat-card *ngFor="let q of questions, let i= index" class="mt20">
<mat-card-content>
<p> Q {{i+1}}) <span [innerHTML]="q.content"></span> </p>
<mat-divider></mat-divider>
<div class="row mt20" >
<div class="col-md-6">
<input type="radio" [value]="q.option1"
[name]="i"
// this is where i am getting error
[(ngModel)] ="q.givenAnswer"
/>
{{q.option1}}
{{i}}
</div>
<div class="col-md-6">
<input type="radio" [value]="q.option2"
[name]="i"
// this is where i am getting error
[(ngModel)] ="q.givenAnswer"
/>
{{q.option2}}
{{i}}
</div>
</div>
<div class="row mt20">
<div class="col-md-6">
<input type="radio" [value]="q.option3"
// this is where i am getting error
[name]="i"
[(ngModel)] ="q.givenAnswer"
/>
{{q.option3}}
{{i}}
</div>
<div class="col-md-6">
<input
type="radio"
[value]="q.option4"
// this is where i am getting error
[name]="i"
[(ngModel)] ="q.givenAnswer"
/>
{{q.option4}}
{{i}}
</div>
</div>
</mat-card-content>
</mat-card>
<div class="container text-center mt20">
<button (click)="submitQuiz()" mat-raised-button color="accent">Submit
Quiz</button>
</div>
</div>
<div class="col-md-2">
</div>
</div>
</div>
</div>
<!-- Show Result -->
<div class="bootstrap-wrapper" *ngIf="isSubmit">
<div class="row">
<div class="col-md-6 offset-md-3">
<mat-card>
<mat-card-header>
<mat-card-title>
<h1 class="text-center mall">Quiz Result</h1>
</mat-card-title>
</mat-card-header>
<mat-card-content>
<h1>Marks Obtained: {{marksGot}}</h1>
<h1>Correct Ansers: {{correctAnswers}}</h1>
<h1>Questions Attempted: {{attempted}}</h1>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button color="accent">Print</button>
<button mat-raised-button color="accent" [routerLink]="'/user-
dashboard/0'">Home</button>
</mat-card-actions>
</mat-card>
</div>
</div>
</div>
Component.ts
import { LocationStrategy } from '#angular/common';
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { QuestionService } from 'src/app/services/question.service';
import Swal from 'sweetalert2';
#Component({
selector: 'app-start-quiz',
templateUrl: './start-quiz.component.html',
styleUrls: ['./start-quiz.component.css']
})
export class StartQuizComponent implements OnInit {
qid;
questions;
marksGot = 0;
correctAnswers = 0;
attempted = 0;
isSubmit = false;
constructor(private locationSt: LocationStrategy, private _route: ActivatedRoute, private
_question: QuestionService) { }
ngOnInit(): void {
this.preventBackButton();
this.qid = this._route.snapshot.params['qid'];
this.loadQuestions();
}
loadQuestions() {
this._question.getQuestionsOfQuizForTest(this.qid).subscribe(
(data: any) => {
this.questions = data;
this.questions.forEach((q) => {
q['givenAnswer'] = '';
});
console.log(data);
},
(error) => {
Swal.fire('Error', 'Error in loading questions of quiz', 'error');
}
);
}
preventBackButton() {
history.pushState(null, null, location.href);
this.locationSt.onPopState(() => {
history.pushState(null, null, location.href);
})
}
submitQuiz() {
Swal.fire({
title: 'Do you want to Submit quiz?',
showCancelButton: true,
confirmButtonText: 'Submit Quiz',
icon: 'info',
}).then((e) => {
if (e.isConfirmed) {
//calculation
this.isSubmit=true;
this.questions.forEach((q) => {
if (q.givenAnswer == q.answer) {
this.correctAnswers++;
let marksSingle = this.questions[0].quiz.maxMarks / this.questions.length;
this.marksGot += marksSingle;
}
if (q.givenAnswer.trim() != '') {
this.attempted++;
}
});
console.log("Correct Answers " + this.correctAnswers);
}
})
}
}
enter image description here
When i am name as [name] it is showing number is not assignable to type String and when i am using name it is compiling successfully but i have three questions in a quiz and while selecting an option of a particular question other options of other questions are getting deselected. what to do?
Thanks in Advance
[(ngModel)]="q.givenAnswer" type="radio" [value]="q.option1" name={{i}}

How to enable only particular card button on checkbox selection

I have running Angular 9 and I want to enable button only when checkbox is clicked. I am using bootstrap cards and each card has its own checkbox and button. The problem I am facing is that whenever I click on any card checkbox, every button of the card gets enabled and vice versa. I want only particular card button to gets enabled or disabled.
test.component.html
<div class="col-3" *ngFor="let data of nominationData">
<form [formGroup]="nominationForm" (ngSubmit)="acceptNomination($event, data)">
<div class="card">
<div class="card-header">
<div class="title">{{data.contributor.name}}</div>
</div>
<div class="card-body">
<div class="row" style="height: 190px;">
<div class="col-sm-12">
<span class="nomination-title">Project Name: </span><div class="desc">{{data.projectName}}</div>
<span class="nomination-title">Posted Date: </span><div class="desc">{{data.nominatedDateTime | date}}</div>
<span class="nomination-title">Technology: </span>
<div *ngFor="let data of data.technology; let i=index" class="tech">
<input type="checkbox" style="margin-right: 10px;" [value]="data"
(change)="onCheckboxChange($event)" />
<label for="chk" style="font-size: 15px;">{{data}}</label>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="buttons">
<button class="btn btn-success" type="submit" [disabled]="!techStack.length">Accept</button>
<button class="btn btn-danger" (click)="rejectNomination(data)">Reject</button>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
test.component.ts
export class TestComponent implements OnInit, OnDestroy {
public search = '';
private nominationSubscription: SubscriptionLike;
nominationForm: FormGroup;
isLoading = false;
techStack: string[] = [];
nominationData: Nomination;
constructor(private fb: FormBuilder, private projectsService: ProjectsService) {
this.nominationForm = this.fb.group({
Technology: this.fb.array([], [Validators.required])
});
}
ngOnInit() {
this.getNominations();
}
getNominations() {
this.isLoading = true;
this.nominationSubscription = this.projectsService.getAllNominations().subscribe(
{
next: (nominations: Nomination) => {
this.nominationData = nominations;
this.isLoading = false;
},
error: (response) => {
this.isLoading = false;
}
}
);
}
onCheckboxChange(e) {
const Technology: FormArray = this.nominationForm.get('Technology') as FormArray;
if (e.target.checked) {
Technology.push(new FormControl(e.target.value));
} else {
let i = 0;
Technology.controls.forEach((item: FormControl) => {
if (item.value === e.target.value) {
Technology.removeAt(i);
return;
}
i++;
});
}
this.techStack = Technology.value;
}
async rejectNomination(data) {
const nomination: Nomination = {
projectId: data.projectId,
contributor: { name: data.contributor.name, emailId: data.contributor.emailId },
// technology: data.technology,
ProjectName: data.projectName
};
await this.projectsService.rejectNomination(nomination);
this.getNominations();
}
async acceptNomination(event, data) {
if (event.submitter.innerHTML === 'Accept') {
const nominatedData = {
ContributorMailId: data.contributor.emailId,
ProjectId: data.projectId,
UserType: 'Contributor',
TechnologiesOpting: this.nominationForm.value.Technology
};
await this.projectsService.acceptNomination(nominatedData);
this.getNominations();
}
}
ngOnDestroy() {
if (this.nominationSubscription) {
this.nominationSubscription.unsubscribe();
}
}
}
The problem in your code is that you have an array of data in nominationData. But the techStack variable is common to all elements of the array. You should have an array of techStack elements also.
// Initialize techStack to be an array of arrays
techStack: string[][] = [];
// In the getNominations function, once you receive the nomination data, insert empty arrays in techStack.
nominationData.forEach(_ => techStack.push([]))
// Modify the onCheckBoxChange function to take an index to indicate checkbox in which item in the list was clicked.
onCheckboxChange(e, index) {
...
this.techStack[index] = Technology.value;
...
}
// In the html, pass this index to the onCheckBoxChange function
<div class="col-3" *ngFor="let data of nominationData; let index=index">
.....
<input
type="checkbox"
style="margin-right: 10px;"
[value]="data"
(change)="onCheckboxChange($event, index)"
/>
....
....
<button
class="btn btn-success"
type="submit"
[disabled]="!techStack[index].length"
>
Accept
</button>
.....
</div>

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 can i add colors to each selected date in js-calender-year using Angular. The color should be persistent after page refresh

I am using js-year-calendar plugin to display all the months in a year at once. However, i can select just one day at a time and then store the date in the database. Please, is there a way to select multiple days e.g. 2020/08/04 - 2020-08-12 and then store this range in the database at once. Meanwhile, i have gone through the documentation but its was not clear to me. Please i need assistance to get a clear picture on how to go about this. Thanks
This is my view. I am sorry for the long code, i really assistance
HTML
<section id="filter" class="mb-3">
<div class="card">
<div class="col-sm-12">
<div class="card-header mt-3">
<div class="card-title-wrap bar-info">
<h4 class="card-title ml-4">{{'ALL_COMPANIES_HOLIDAY_CALENDER' | translate}}</h4>
</div>
</div>
<div class="card-body">
<div class="card-block">
<div class="row">
<div class="col-md-6 col-lg-6">
<div class="row">
<div class="col-md-4 col-lg-4 col-12 mt-1 ml-4">
<div class="form-group row">
<div class="col-md-12 searchcat">
<select class="form-control " [(ngModel)]="holidays.company_id" id="company" name="company" (change)="getSelectedCompany(holidays.company_id)" required>
<option value="" disabled selected hidden>{{'SELECT_COMPANY' | translate}}</option>
<option *ngFor="let data of companyList; let i = index" [value]="data.id" >{{data.company_name}}</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-5 ml-2">
<div class="col-md-12 col-lg-12">
<div id="calendar">
</div>
</div>
</div>
<div class="card-body">
<div class="card-block">
<div class="clearfix"></div>
<ngx-datatable #table class='bootstrap' [columnMode]="'force'" [headerHeight]="50" [footerHeight]="50"
[rowHeight]="'auto'" [limit]="50" [rows]='holidaysDataRows'>
<ngx-datatable-column name="{{'COMPANY_NAME' | translate}}" prop="company_name"></ngx-datatable-column>
<ngx-datatable-column name="{{'YEAR' | translate}}" prop="year"></ngx-datatable-column>
<ngx-datatable-column name="{{'HOLIDAY' | translate}}" prop="holidays_date">
</ngx-datatable-column>
<ngx-datatable-column name="{{'DESCRIPTION' | translate}}" prop="description" > </ngx-datatable-column>
<ngx-datatable-column name="{{'ACTIONS' | translate}}" prop="status">
<ng-template ngx-datatable-cell-template let-rowIndex="rowIndex" let-value="value" let-row="row"
let-group="group" let-rowHeight="rowHeight">
<button (click)="editHoliday(editModal,row)" class="btn btn-raised mr-1 shadow-z-2 btn-info btn-sm ">{{'EDIT' | translate}}</button>
<button (click)="deleteModal(deleteholiday, row.holiday_id)" class="btn btn-raised mr-1 shadow-z-2 btn-danger btn-sm ">{{'DELETE' | translate}}</button>
</ng-template>
</ngx-datatable-column>
</ngx-datatable>
<div class="loader-div" *ngIf="showLoader">
<img src="assets/img/portrait/small/loader.gif" alt="spinner" class="loader">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
TS CODE
import { Component, OnInit, ViewChild } from '#angular/core';
import { SnotifyService } from 'ng-snotify';
import { Router, ActivatedRoute } from "#angular/router";
import { NgbModal, ModalDismissReasons, NgbActiveModal } from '#ng-bootstrap/ng-bootstrap';
import { HumanResourceService } from 'app/services/human-resource/human-resource.service';
import { TranslateService } from '#ngx-translate/core';
import { AuthenticationService } from 'app/services/authentication/authentication.service';
import { HumanResourceMasterService } from '../../../services/human-resource-master/human-resource-master.service';
import Calendar from 'js-year-calendar';
import * as moment from 'moment';
import { GlobalConstants } from 'app/shared/constants/global-constants';
#Component({
selector: 'app-all-company-holiday-calender',
templateUrl: './all-company-holiday-calender.component.html',
styleUrls: ['./all-company-holiday-calender.component.scss']
})
export class AllCompanyHolidayCalenderComponent implements OnInit {
#ViewChild('openModal') OpenModalotdeletepos;
companyList: any = [];
company_id: any = '';
datas: any;
dateFromModal : any;
closeResult: any;
currentHolidays: any = [];
holidaysDataRows: [];
HolidayDeleteData: any;
showLoader: boolean;
deleterowid: any;
holidaysData : any = [];
holidays: any = {
description: '',
date: '',
company_id:'',
hr_id: '',
hols_id: '',
}
selectedDate:any;
hrID: any;
eventDate: Date;
eventText: string;
myEvents: any[] = [];
constructor(private snotifyService: SnotifyService,private spinner:
FullLayoutComponent, private
route: ActivatedRoute, private modalService: NgbModal, private
loginService: LoginService,private hrMasterService:
HumanResourceMasterService, private hrService:
HumanResourceService, public authService: AuthenticationService,public
translate: TranslateService) {
ngOnInit() {
this.getDate();
}
getDate(){
var modalService = this.modalService;
var snotifyService = this.snotifyService;
var openModal = this.OpenModalotdeletepos;
var getDismiss = this.getDismissReason;
new Calendar('#calendar');
var holiday = this.holidays;
var translate = this.translate;
document.querySelector('#calendar').addEventListener('clickDay',
function(data) {
var hols = moment(data['date']).format(GlobalConstants.DATE_FORMAT);;
holiday.date = hols;
if(!holiday.company_id){
snotifyService.error(translate.instant('MESSAGE_PLEASE_SELECT_COMPANY'));
}
else{
modalService.open(openModal).result.then((result) => {
this.closeResult = GlobalConstants.CLOSE + `${result}`;
}, (reason) => {
this.closeResult = GlobalConstants.DISMISSED +
`${getDismiss(reason)}`;
});
}
})
}
getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return GlobalConstants.PRESS_ESC;
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return GlobalConstants.BACKDROP_CLICK;
} else {
return GlobalConstants.WITH + ` ${reason}`;
}
}
getHolidayData(){
this.showLoader = true;
this.hrMasterService.getHolidayData({}).subscribe(data => {
if(data.status_code = 200){
this.showLoader = false;
this.holidaysData = data.data;
this.holidaysDataRows = this.holidaysData;
}
else {
this.showLoader = false;
this.snotifyService.error(data.message);
}
})
}
saveHolidays(){
this.holidays.hr_id = this.hrID.id;
this.hrMasterService.createHolidays(this.holidays).subscribe(data =>{
if(data.status_code = 200){
this.snotifyService.success(this.translate.instant('MESSAGE_HOLIDAY_CREATED'));
this.modalService.dismissAll();
setTimeout(() => {
window.location.reload();
}, 1000);
} else {
this.snotifyService.error(data.message);
}
},error=>{
});
}
onChangeDate(holiday){
}
getSelectedCompany(company_id: any){
}
}
Replace new Calendar('#calendar') with new Calendar('#calendar',{enableRangeSelection: true});
then you can get it here:
document.querySelector('#calendar').addEventListener('selectRange', function(e) {
console.log("Select the range: " + e.startDate + " - " + e.endDate);
})
Year Calendar Documentaion
Here is a Stackblitz

Show Only One Value In Dropdown If There are Duplicates

Hi i'm trying to get the information of printers by the location. so if i have few printers at the same location ill see them both at the dropdown but i actually want to see only one location on the dropdown if they are the same location.
i know i can solve this in the database level and add relationships but maybe there is a way to do it without it ?
import {
Component,
OnInit
} from '#angular/core';
import {
HttpClient
} from '#angular/common/http';
import {
DomSanitizer
} from '#angular/platform-browser';
import {
Values
} from '../Models/Values';
#Component({
selector: 'app-value',
templateUrl: './value.component.html',
styleUrls: ['./value.component.css']
})
export class ValueComponent implements OnInit {
selectedPrinter: Values;
values: any;
constructor(private http: HttpClient, public sanitizer: DomSanitizer) {}
ngOnInit() {
this.getValues();
}
getValues() {
this.http.get('http://localhost:5000/api/values/').subscribe(response => {
this.values = response;
}, error => {
console.log(error);
})
}
}
<H2>Printer Manager</H2>
<div id="selectCompanyDiv">
<div class="col-12 col-md-3 col-xl-2 mt-5 bd-sidebar">
<label for="">Select Location</label>
<select class="form-control" [(ngModel)]="selectedPrinter">
<option *ngFor="let each of values " [ngValue]="each.location">{{each.location}} </option>
<!-- {{each.specificLocation}} -->
</select>
<!-- Search -->
<!-- <input id="test" *ngFor="let each of values " class="form-control" type="search" placeholder="Search" {{values.location}}>
<button ondblclick="Access()">click here
</button> -->
</div>
<br>
<br>
<div>
<div *ngFor="let value of values" id="mainDiv">
<div *ngIf="value.location===selectedPrinter">
<span>HostName: {{value.hostName}}</span>
<br>
<!-- <span>Location: {{value.location}}</span> -->
<span>Manufacturer: {{value.manufacturer}}</span>
<br>
<span>IP: {{value.ip}}</span>
<br>
<h2>{{value.location}}</h2>
<span>{{value.specificLocation}}</span>
<br>
<a target="_blank" [href]="sanitizer.bypassSecurityTrustResourceUrl('http://'+value.ip+'/general/status.html')">Full view</a>
<div>
<div *ngIf="value.model==='J480'" class="outerFrame">
<iframe [src]="sanitizer.bypassSecurityTrustResourceUrl('http://'+value.ip+'/general/status.html')" id="inneriframeBrotherj480" scrolling="no"></iframe>
</div>
<div *ngIf="value.model==='6530DW'" class="outerFrame">
<iframe [src]="sanitizer.bypassSecurityTrustResourceUrl('http://'+value.ip+'/general/status.html')" id="inneriframeBrother6530DW" scrolling="no"></iframe>
</div>
</div>
</div>
</div>
getValues() {
this.http.get('http://localhost:5000/api/values/').subscribe(response => {
this.values = [...new Set(response)];
}, error => {
console.log(error);
})
}
What i would do is the following:
In getValues():
getValues() {
this.http.get('http://localhost:5000/api/values/').subscribe(response => {
this.values = Array.from(new Set(response));
}, error => {
console.log(error);
})
}
Take a look at Array.from documentation and Array.from(set)
Good luck!

Categories

Resources