Как мне выполнить два списка mat-chip-списков в одной форме, извлекая их из двух отдельных таблиц базы данных? - PullRequest
0 голосов
/ 16 октября 2019

Я пишу форму для выполнения поиска по введенным критериям. Я сосредоточен на школах и этапах найма. Школы и этапы найма должны быть списками, чтобы можно было выбрать более одного варианта. Школы работают, но нанимать сцен не работает. Как мне заставить их работать как списки mat-chip-списков в одной форме?

HTML

    <mat-grid-tile colspan="4" rowspan="4">
        <div class='eForm'>
            <form [formGroup]='searchForm' autocomplete='off' novalidate (ngSubmit)="onSubmit()">
                <mat-form-field class="nameSearch">
                    <span matPrefix>Name:&nbsp;</span>
                    <input matInput id = 'firstName' placeholder="&nbsp;Enter candidate name">
                </mat-form-field>
                <mat-form-field class="majorSearch">
                    <span matPrefix>Major:&nbsp;</span>
                    <input matInput placeholder="&nbsp;Enter candidate major">
                </mat-form-field>

                <tr>
                    <mat-form-field *ngIf = "schoolSource" class="schools">
                        <mat-label>Schools</mat-label>
                        <mat-chip-list #chipList>
                            <mat-chip *ngFor = "let school of schools"
                            [selectable] = "true"
                            [removable] = "true"
                            (removed) = "removeSchool(school)">
                            {{ school }}
                            <mat-icon matChipRemove *ngIf = "removable">cancel</mat-icon>
                            </mat-chip>
                            <input placeholder = "Choose school(s)" #schoolInput
                                [formControl] = "schoolCtrl"
                                [matAutocomplete]="auto"
                                [matChipInputFor]="chipList"
                                [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
                                [matChipInputAddOnBlur]="addOnBlur">
                        </mat-chip-list>

                        <mat-autocomplete #auto (optionSelected)="selectedSchool($event)">
                            <mat-option *ngFor="let school of schoolSource"
                            [value] = 'schoolId'>
                            {{ school.schoolName }}
                            </mat-option>
                        </mat-autocomplete>
                    </mat-form-field>

                    <mat-form-field *ngIf = "hireStageSource" class="hireStages">
                        <mat-label>Hire Stage</mat-label>
                        <mat-chip-list #chipList1>
                            <mat-chip *ngFor = "let hireStage of hireStages"
                            [selectable] = "true"
                            [removable] = "true"
                            (removed) = "removeStage(hireStage)">
                            {{ hireStage }}
                            <mat-icon matChipRemove *ngIf = "removable">cancel</mat-icon>
                            </mat-chip>
                            <input placeholder = "Choose Hire Stage(s)" #hireStageInput
                            [formControl] = "hireStageCtrl"
                            [matAutoComplete] = "auto1"
                            [matChipInputFor] = "chipList1"
                            [matChipInputSeparatorKeyCodes] = "separatorKeysCodes"
                            [matChipInputAddOnBlur] = "addOnBlur">
                        </mat-chip-list>

                        <mat-autocomplete #auto1 (optionSelected) = "selectedStage($event)">
                            <mat-option *ngFor = "let hireStage of hireStageSource"
                            [value] = 'stageId'>
                            {{ hireStage.stageName }}
                            </mat-option>
                        </mat-autocomplete>
                        <!-- <mat-select [(value)]="stageId">
                            <mat-option id=stageId *ngFor="let hireStage of hireStages" [value]="hireStage.stageId">
                                {{hireStage.stageName}}
                            </mat-option>
                        </mat-select> -->
                    </mat-form-field>
                </tr>
                <mat-form-field class="startDate">
                    <input matInput [matDatepicker]="picker" placeholder="Choose a start date"
                        id="startDate" name="startDate">
                    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
                    <mat-datepicker #picker></mat-datepicker>
                </mat-form-field>

                <mat-form-field class="endDate">
                    <input matInput [matDatepicker]="picker2" placeholder="Choose an end date"
                        id="endDate" name="endDate">
                    <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
                    <mat-datepicker #picker2></mat-datepicker>
                </mat-form-field>
            </form>
        </div>
    </mat-grid-tile>
    <mat-grid-tile colspan="6" rowspan="4">2</mat-grid-tile>
    <mat-grid-tile colspan="4" rowspan="6">3</mat-grid-tile>
    <mat-grid-tile colspan="6" rowspan="6">4</mat-grid-tile>
</mat-grid-list>
<div *ngIf="hireStageSource">
    <div *ngFor='let hireStage of hireStageSource'> {{hireStage.stageName}} </div>
</div>

.ts

import { Location } from '@angular/common';
import { School } from 'src/app/services/database-services/school';
import { FormGroup, FormControl } from '@angular/forms';
import { SchoolService } from 'src/app/services/database-services/school.service';
import { HireStage } from 'src/app/services/database-services/hirestage';
import { HireStageService } from 'src/app/services/database-services/hirestage.service';
import { ENTER, COMMA } from '@angular/cdk/keycodes';
import { Observable } from 'rxjs';
import { MatAutocomplete, MatAutocompleteTrigger, MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';
import { MatChipInputEvent } from '@angular/material';

@Component({
    selector: 'send-email-templates',
    templateUrl: './send-email-templates.html',
    styleUrls: ['./send-email-templates.css'],
})
export class SendEmailTemplatesComponent implements OnInit {

        //this is where schools are stored
    public schoolSource: School[];
    public hireStageSource: HireStage[];



    // Stuff for school & hire stage selection //
    visible = true;
    selectable = true;
    removable = true;
    addOnBlur = true;
    separatorKeysCodes: number[] = [ENTER, COMMA];
    schoolCtrl = new FormControl();
        //this is the array that gets displayed
    schools: string[] = [];
    allSchools: School[];
    allHireStages: HireStage[];
    hireStages: string[] = [];
    hireStageCtrl = new FormControl();

    // List of Id's for schools and hire stages to be searched //
    schoolIdList: number[] = [];
    hireStageIdList: number[] = [];
    @ViewChild('schoolInput', {static: false}) schoolInput: ElementRef<HTMLInputElement>;
    @ViewChild('auto', {static: false}) matAutocomplete: MatAutocomplete;
    @ViewChild('hireStageInput', {static: false}) hireStageInput: ElementRef<HTMLInputElement>;
    @ViewChild('auto1', {static: false}) matAutocomplete1: MatAutocomplete;
    // @ViewChild(MatAutocompleteTrigger, {static: false}) trigger: MatAutocompleteTrigger;

    searchForm = new FormGroup({

    });

    constructor(
        private schoolService: SchoolService,
        private hireStageService: HireStageService,
    ) { }


    ngOnInit() {
        this.getSchools();
        this.getHireStages();
    }

    getSchools(): void {
        this.schoolService.getSchools().subscribe(schools => {
        this.schoolSource = schools;
        for(let school of this.schoolSource){
            console.log(school.schoolName);
        }
        console.log(this.schools.length)
        });
    }

    getHireStages(): void {
        this.hireStageService.getHireStages().subscribe(hireStages => {
        this.hireStageSource = hireStages;
        for(let stage of this.hireStageSource){
            console.log(stage.stageName)
            console.log(this.hireStages.length)
        }
        });
    }

    removeSchool(school: string): void {
        const index = this.schools.indexOf(school);
        if (index >= 0) {
            this.schools.splice(index, 1);
            this.schoolIdList.splice(index, 1);
        }
    }

    removeStage(hireStage: string): void {
        const index = this.hireStages.indexOf(hireStage);
        if (index >= 0) {
            this.hireStages.splice(index, 1);
            this.hireStageIdList.splice(index, 1);
        }
    }

    selectedSchool(event: MatAutocompleteSelectedEvent): void {
        if (!this.schools.includes(event.option.viewValue)) {
            this.schools.push(event.option.viewValue)

            this.schoolIdList.push(event.option.value);
        }
        this.schoolInput.nativeElement.value = '';
        this.schoolCtrl.setValue(null);
        document.getElementById('firstName').click();
    }

    selectedStage(event: MatAutocompleteSelectedEvent): void {
        if (!this.hireStages.includes(event.option.viewValue)) {
            this.hireStages.push(event.option.viewValue)

            this.hireStageIdList.push(event.option.value);
        }

        this.hireStageInput.nativeElement.value = '';
        this.hireStageCtrl.setValue(null);
        document.getElementById('firstName').click();
    }

    private _filter(value: School): School[] {
        return this.allSchools.filter(school => this.allSchools.indexOf(school) === 0);
    }

    private _filter1(value: HireStage): HireStage[] {
        return this.allHireStages.filter(hireStage => this.allHireStages.indexOf(hireStage) === 0);
    }

}```

1 Ответ

0 голосов
/ 16 октября 2019

Так что я хочу пойти дальше и ответить на свой вопрос здесь. Единственная проблема с этим кодом - со вторым matAutocomplete в HTML. Я указал его как [matAutoComplete] = "auto1", когда он должен быть [matAutocomplete] = "auto1" со строчной буквой c. Это исправило все.

...