Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { CarsService } from '../services/cars.service';
- import { Car } from './../models/car';
- import { Component, OnInit } from '@angular/core';
- import { BrandCB } from '../models/brandCB';
- @Component({
- selector: 'app-gallery',
- templateUrl: './gallery.component.html',
- styleUrls: ['./gallery.component.css']
- })
- export class GalleryComponent implements OnInit {
- cars:Car[];
- brands:BrandCB[] = [];
- selectedBrand:string;
- checkboxAll:any = {checked:true};
- observableCars;
- observableBrands;
- constructor(public carsService: CarsService) {
- }
- ngOnInit() {
- this.getCars();
- this.observableBrands = this.carsService.getBrands().subscribe( (data:any) => {
- for(let i=0;i<data.length;i++){
- this.brands.push(new BrandCB(data[i].brand, false));
- }
- });
- }
- getCars(){
- this.observableCars = this.carsService.getCars().subscribe(data => {
- this.cars = [];
- // checkboxAll è la checkbox che permette di prendere tutti gli elementi dell array
- if(!this.checkboxAll.checked){
- // array con solo i brand selezionati e con solo i brand senza altre proprietà
- const checkedBrands = this.brands.filter(brand => brand.checked);
- // filtro i dati dal server prelevando solo quelli che hanno un brand presente in checkedBrands
- this.cars = data.filter(car => checkedBrands.find(brand => brand.brand === car.brand));
- this.cars.sort((a,b) => a.brand.localeCompare(b.brand));
- } else {
- this.cars = data;
- }
- });
- }
- checkboxChange(event){
- let name = event.target.name;
- let checked = event.target.checked;
- if(name=='all'){
- if(checked==true){
- for(let i=0;i<this.brands.length;i++){
- this.brands[i].checked = false;
- }
- }
- } else {
- if(checked==true){
- // checkbox all = unchecked
- this.checkboxAll.checked = false;
- } else {
- let isOneChecked:boolean = false;
- for(let i=0;i<this.brands.length;i++){
- if(this.brands[i].checked)
- isOneChecked = true;
- }
- if(!isOneChecked)
- this.checkboxAll.checked = true;
- }
- }
- this.getCars();
- }
- ngOnDestroy(){
- this.observableCars.unsubscribe();
- this.observableBrands.unsubscribe();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement