как переключать вкладку при нажатии кнопки сохранения или как привязать кнопку сохранения для переключения вкладки - PullRequest
0 голосов
/ 08 июля 2020

import { Component, OnInit, OnDestroy } from '@angular/core';
import {
    FormGroup,
    FormControl,
    Validators,
    FormArray
} from '@angular/forms';
import { CustomValidators } from 'ng2-validation';
import {
    BusinessGQL,
    SitedatasGQL,
    SiteData,
    UpdateBusinessGQL,
    Business
} from 'src/app/graphql';
import { ActivatedRoute, Router } from '@angular/router';
import { map, take, pluck } from 'rxjs/operators';
import { log, removeTypename } from 'src/app/shared/functions';
import { CategoryService } from 'src/app/shared/services/category.service';
import { LocationService } from 'src/app/shared/services/location.service';
import { AddbusinessService } from 'src/app/shared/services/Addbusiness.service';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { Config } from 'src/app/config/config';
import { Subscription } from 'rxjs';

@Component({
    selector: 'app-add-business',
    templateUrl: './add-business.component.html',
    styleUrls: ['./add-business.component.scss']
})
export class AddBusinessComponent implements OnInit, OnDestroy {
    isCollapsed = false;
    activeTab="General Information"
    siteDatas: SiteData[] = [];
    logoImage = `url('../../../../assets/images/download.jpeg')`;
    bannerImage = '';

    businessSubscription: Subscription;

    form = new FormGroup({
        _id: new FormControl('', [Validators.required]),
        name: new FormGroup({
            en: new FormControl('', [Validators.required]),
            ar: new FormControl('')
        }),
        photos: new FormArray([]),
        email: new FormControl('', [Validators.required, CustomValidators.email]),
        phone: new FormControl('', [Validators.required]),
        website: new FormControl('', [Validators.required]),
        licesenceNumber: new FormControl(''),
        licesenceExpiryDate: new FormControl(''),
        description: new FormGroup({
            en: new FormControl(''), // [Validators.required]
            ar: new FormControl('') // [Validators.required]
        }),
        budgetManaged: new FormControl(''),
        numberOfEmployees: new FormControl(''),
        numberOfProjectsComplete: new FormControl(''),
        // workingHours: new FormArray([
        //   new FormGroup({
        //     day: new FormControl('', []),
        //     from: new FormControl('', []),
        //     to: new FormControl('', []),
        //   })
        // ]),
        contactPerson: new FormGroup({
            name: new FormControl('', []),
            // new FormGroup({
            //   en: new FormControl('', [Validators.required]),
            //   ar: new FormControl('', [Validators.required])
            // }),
            email: new FormControl('', [
                Validators.required,
                CustomValidators.email
            ]),
            phone: new FormControl('', [Validators.required]),
            position: new FormControl('', [Validators.required])
        }),
        categories: new FormArray([]),
        scopes: new FormArray([]),
        countries: new FormArray([new FormControl('', [Validators.required])]),
        cities: new FormArray([
            new FormGroup({
                city: new FormControl('', [Validators.required]),
                address: new FormControl('', [Validators.required]),
                coordinates: new FormGroup({
                    latitude: new FormControl('', [Validators.required]),
                    longitude: new FormControl('', [Validators.required])
                }),
                type: new FormControl(),
                photos: new FormArray([])
            })
        ]),
        status: new FormControl('', [Validators.required]),

        // extra
        category: new FormControl('')
    });

    generalForm = new FormGroup({
        _id: new FormControl('', Validators.required),
        name: new FormGroup({
            en: new FormControl(''),
            ar: new FormControl('')
        }),
        description: new FormGroup({
            en: new FormControl(),
            ar: new FormControl()
        }),
        email: new FormControl(''),
        phone: new FormControl(''),
        website: new FormControl(''),
        details: new FormGroup({
            businessType: new FormControl(''),
            businessClass: new FormControl(),
            serviceArea: new FormControl(),
            projectSize: new FormControl(),
            budgetsManaged: new FormGroup({
                min: new FormControl(),
                max: new FormControl()
            }),
            yearOfEstablishment: new FormControl(),
            numberOfEmployees: new FormControl(),
            licenseNumber: new FormControl(),
            numberOfProjectsCompleted: new FormControl()
        }),
        operationalHours: new FormGroup({
            startDay: new FormGroup({
                en: new FormControl(),
                ar: new FormControl()
            }),
            endDay: new FormGroup({
                en: new FormControl(),
                ar: new FormControl()
            }),
            shifts: new FormArray([])
        }),
        contactPerson: new FormGroup({
            name: new FormGroup({
                en: new FormControl(),
                ar: new FormControl()
            }),
            email: new FormControl(),
            phone: new FormControl(),
            position: new FormControl()
        })
    });

    //
    locations: any[] = [];

    team: any[] = [];

    certificates: any[] = [];
    verifications: any[] = [];

    user: any;

    categories: any[] = [];
    subCategories: any;
    services: any[];
    countries: any;
    cities: any;
    scopes: any[] = [];
    subCategoriesArray: any[] = [];
    currentBusiness: Business;
    fisrt = true;
    successMessage = '';
    errorMessage = '';

    albums: any[] = [];

    constructor(
        private activatedRoute: ActivatedRoute,
        private businessGQL: BusinessGQL,
        private categoryService: CategoryService,
        private router: Router,
        private locationService: LocationService,
        private updateBusinessGQL: UpdateBusinessGQL,
        private modalService: NgbModal,
        private sitedatasGQL: SitedatasGQL,
        private AddbusinessService:AddbusinessService
    ) {
        this.categoryService.categories.pipe(take(2)).subscribe(categories => {
            this.categories = categories;
        });
        this.locationService.countries.pipe(take(1)).subscribe(countries => {
            this.countries = countries;
        });
        this.cities = this.locationService.cities;

        this.sitedatasGQL
            .watch()
            .valueChanges.pipe(pluck('data', 'sitedatas'))
            .subscribe((response: SiteData[]) => {
                this.siteDatas = response;
            });
    }

    getCountry(country) {
        const _country = (this.countries || []).find(c => c._id == country);
        return _country ? _country.name.en : '';
    }

    setLocations(business) {
        this.locations = business.cities;
    }

    setCertificates(business) {
        this.certificates = business.certficates;
    }

    setVerifications(business) {
        this.verifications = business.verifications;
    }

    setUser(business) {
        this.user = business.user;
    }

    categorySelected(category) {
        if (category) {
            const formCategoriesArray = this.form.get('categories') as FormArray;
            while (formCategoriesArray.length !== 0)
                formCategoriesArray.removeAt(0);
            formCategoriesArray.push(new FormControl(category));
            this.setSubCategories(category);
            const formScopesArray = this.form.get('scopes') as FormArray;
            if (!this.fisrt)
                while (formScopesArray.length !== 0) formScopesArray.removeAt(0);
            this.scopes = this.categories.find(
                cateogry => cateogry._id == category
            ).scopes;
            this.fisrt = false;
        }
        this.fisrt = false;
    }
    setSubCategories(category) {
        this.subCategories = this.categories.find(
            cateogry => cateogry._id == category
        ).subCategories;
    }

    checkSubCategoryCheck(subCatgory) {
        this.categoryService.subSubCategories;
        return true;
    }

    selectSubCategory(event, subCategoryId) {
        const checked = event.target.checked || true;
        const categories = this.subCategories.find(
            category => category._id === subCategoryId
        ).subCategories;
        const categoriesArray = this.form.get('categories') as FormArray;
        if (checked) {
            categoriesArray.push(new FormControl(subCategoryId));
            categories.forEach(category => {
                categoriesArray.push(new FormControl(category._id));
            });
        } else {
            const index = categoriesArray.value.indexOf(subCategoryId);
            categoriesArray.removeAt(index);
            categories.forEach(category => {
                const index = categoriesArray.value.indexOf(category._id);
                categoriesArray.removeAt(index);
            });
        }
    }

    setScope(event, scope) {
        const checked = event.target.checked;
        const scopeArray = this.form.get('scopes') as FormArray;
        if (checked) {
            scopeArray.push(new FormControl(scope));
        } else {
            const index = scopeArray.value.indexOf(scope);
            scopeArray.removeAt(index);
        }
    }

    setCoordinates(cityId) {
        const city = this.cities.find(city => city._id == cityId);
        this.form
            .get('cities.0.coordinates.latitude')
            .setValue(city.coordinates.latitude);
        this.form
            .get('cities.0.coordinates.longitude')
            .setValue(city.coordinates.longitude);
    }

    setTeam(business) {
        this.team = business.team;
    }

    remove(index) {
        this.activatedRoute.params.subscribe(({ id }) => {
            const _team = [...this.team];
            _team.splice(index, 1);
            const json: any = {
                team: _team.map(member => ({
                    user: member.user ? member.user._id : member.userId,
                    userId: member.userId,
                    type: member.type._id,
                    status: member.status
                }))
            };

            json._id = id;
            this.updateBusinessGQL
                .mutate(json, {
                    refetchQueries: [
                        {
                            query: this.businessGQL.document
                        }
                    ]
                })
                .subscribe();
        });
    }

    setAlbum(business) {
        this.albums = business.albums;
    }

    encodeUrl(url) {
        return `url(${Config.s3url}${encodeURI(url)})`;
    }

    removeAlbum(index) {
        this.activatedRoute.params.subscribe(({ id }) => {
            const _albums = [...this.albums];
            _albums.splice(index, 1);
            const json: any = {
                albums: removeTypename(_albums).map(a => ({
                    ...a,
                    photos: a.photos.map(p => p._id)
                }))
            };

            json._id = id;
            this.updateBusinessGQL
                .mutate(json, {
                    refetchQueries: [
                        {
                            query: this.businessGQL.document
                        }
                    ]
                })
                .subscribe();
        });
    }

    onSubmit() {
        // this.frmSubmited = true
        const frmData = this.form.value;
        log(frmData);
        this.updateBusinessGQL
            .mutate(frmData)
            .pipe(map(response => response['data']['updateBusiness']))
            .subscribe(
                response => {
                    log('business updated', response);
                    this.successMessage = 'Bussiness Updated.';
                },
                ({ networkError, graphQLErrors }) => {
                    if (networkError) {
                        this.errorMessage = networkError[0].message;
                    } else if (graphQLErrors) {
                        this.errorMessage = graphQLErrors[0].message;
                    } else {
                        this.errorMessage = 'Something went wrong!';
                    }
                }
            );
    }

    scopeChecked(val) {
        return this.currentBusiness.scopes.includes(val);
    }

    subCategoryChecked(val) {
        return this.currentBusiness.categories.map(x => x._id).includes(val);
    }

    ngOnInit() {
        this.activatedRoute.queryParams.subscribe(({activeState})=>{
            this.activeTab=activeState||"General Information"
        })
        this.activatedRoute.params.subscribe(({ id }) => {
            this.businessSubscription = this.businessGQL
                .watch({ _id: id }, { fetchPolicy: 'no-cache' })
                .valueChanges.pipe(map(response => response.data.business))
                .subscribe(business => {
                    if (business) {
                        this.currentBusiness = business as Business;
                        // this.setGeneralFormData(business);
                        this.setLocations(business);
                        this.setTeam(business);
                        this.setAlbum(business);
                        this.setCertificates(business);
                        this.setVerifications(business);
                        this.setUser(business);
                    } else {
                        alert('[ERROR]: Invalid business');
                        this.router.navigate(['..']);
                    }
                });
        });

        this.form.get('category').valueChanges.subscribe(val => {
            this.categorySelected(val);
        });
    }

    ngOnDestroy() {
        this.businessSubscription.unsubscribe();
    }
}
<h4> Add Business </h4>
<div>
    <div class="container">
        <tabset type="pills">
            <tab heading="General Information" id="tab1" [active]="activeTab=='General Information'">
                <add-general [siteDatas]="siteDatas" [business]="currentBusiness">
                </add-general>
            </tab>
            <tab heading="Tags" [active]="activeTab=='Tags'">
                <app-add-tags>
                </app-add-tags>
            </tab>
            <tab heading="Location" [active]="activeTab=='Location'">
                <app-add-locat [locations]="locations" [countries]="countries">
                </app-add-locat>
            </tab>

            <tab heading="Team" id="tab1" [active]="activeTab=='Team'">
                <app-team>
                </app-team>
            </tab>
            <!-- Tab 5 End -->

            <!-- Tab 6  Gallery-->
            <tab heading="Gallery" [active]="activeTab=='Gallery'">
                <app-add-gallerys>
                </app-add-gallerys>
            </tab>
            <!-- Tab 6 End -->

            <!-- Tab 7 Social-->
            <tab heading="Social" id="tab1" [active]="activeTab=='Social'">
                <add-social>
                </add-social>
            </tab>
            <!-- Tab 7 End -->

            <!-- Tab 8 Certification-->
            <tab heading="Certificate" id="tab2" [active]="activeTab=='Certificate'">
                <add-certificates>
                </add-certificates>
            </tab>

            <tab heading="Verification" id="tab1" [active]="activeTab=='Verification'">
                <add-verification>
                </add-verification>
            </tab>
          

        </tabset>
    </div>
изображение моей страницы

У меня есть вкладки, на которые я хочу связать действие, которое, когда я нажимаю кнопку «Сохранить» или «Отправить», я могу автоматически переходить от вкладки к другой. Может ли кто-нибудь отредактировать мой код, чтобы переключить вкладку на кнопке сохранения, как я могу это реализовать. здесь я включаю свой код Html и файл js. здесь я использую angular, чтобы написать свое приложение

1 Ответ

1 голос
/ 08 июля 2020

Попробуйте это ..

Метод 1:

.ts

      index = 0;
      activeTab = "General Information";

      onSave() {
        index++;
        switch (index) {
          case 1: this.activeTab = "Tags";  break;
          case 2: this.activeTab = "Location";  break;
          case 3: this.activeTab = "Team";  break;
          // similarly add case for all tabs
        }

        // your logic
      }

чтобы свойство [active] проверялось, чтобы определить, какая вкладка активна при каждом нажатии кнопки сохранения (предполагается, что кнопка сохранения является общей для всех вкладок) ..

Метод 2:

. html

<button (click)="save1()">Save</button>  // 1st tab's save button
<button (click)="save2()">Save</button>  // 2nd tab's save button
<button (click)="save3()">Save</button>  // 3rd tab's save button
// Similarly add save button for all tabs based on next tabs id

.ts

// 1st tab's save button
save1() { 
  this.activeTab = "Tags"

  // your logic
}

save2() {
  this.activeTab = "Location"

  // your logic
}

save3() {
  this.activeTab = "Team"

  // your logic
}

Примечание. Используйте существующие методы сохранения в место save1, save2, et c

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...