【问题标题】:How to switch tab on clicking save button or how to bind the save button to switch tab如何在单击保存按钮时切换选项卡或如何将保存按钮绑定到切换选项卡
【发布时间】:2020-10-29 07:23:04
【问题描述】:

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 = 'Business 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 代码和 component.js 文件。这里我使用 Angular 来编写我的应用程序

【问题讨论】:

    标签: javascript html angular twitter-bootstrap


    【解决方案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] 属性以确定每次单击保存按钮时哪个选项卡处于活动状态(假设保存按钮对所有选项卡都是通用的)..

    方法二:

    .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 等

    【讨论】:

    • 所有标签的点击按钮都不一样
    • 好的,那么您可以在当前选项卡的保存按钮单击时将下一个选项卡的标题设置为 activeTab..
    • 我已经更新了代码..在我的答案中检查方法2..
    猜你喜欢
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多