角材料:在特定条件下如何刷新下拉列表?

时间:2019-06-11 08:24:54

标签: javascript angular typescript angular-material dropdown

我有一个下拉列表,我想刷新值,更确切地说,我有两种语言,并且对于每种语言,我都有那些元素[name-代表英语,namecz代表捷克语],如果值是“ English “对于英语来说,捷克语将是捷克语,到目前为止,即使选择正确的值,我也设法显示了每种语言的列表,我的问题是,如果我更改语言,则所选值保持不变,不会改变

这是我想要获得的类似示例。 https://stackblitz.com/edit/angular-jfetuh?file=app%2Fselect-value-binding-example.html

这是我的有效载荷:

[{id: 19, name: "Travel Recreation and Leisure", nameCZ: "test19"},…]
0: {id: 19, name: "Travel Recreation and Leisure", nameCZ: "test19"}
1: {id: 20, name: "Wholesale and Distribution", nameCZ: "test20"}
2: {id: 1, name: "Agriculture and Mining", nameCZ: "test1", description: "hello"}
3: {id: 2, name: "Business Services", nameCZ: "test2"}
4: {id: 3, name: "Computer and Electronics", nameCZ: "test3"}
5: {id: 4, name: "Consumer Services", nameCZ: "test4"}
6: {id: 5, name: "Education", nameCZ: "test5"}
7: {id: 6, name: "Energy and Utilities", nameCZ: "test 6"}
8: {id: 7, name: "Financial Services", nameCZ: "test 7"}
9: {id: 8, name: "Government", nameCZ: "test 8"}
10: {id: 9, name: "Health, Pharmaceuticals, and Biotech", nameCZ: "test9"}
11: {id: 10, name: "Manufacturing", nameCZ: "test10"}
12: {id: 11, name: "Media and Entertainment", nameCZ: "test11"}
13: {id: 12, name: "Non-profit", nameCZ: "test12"}
14: {id: 13, name: "Other", nameCZ: "test13"}
15: {id: 14, name: "Real Estate and Construction", nameCZ: "test14"}
16: {id: 15, name: "Retail", nameCZ: "test15"}
17: {id: 16, name: "Software and Internet", nameCZ: "test16"}
18: {id: 17, name: "Telecommunications", nameCZ: "test17"}
19: {id: 18, name: "Transportation and Storage", nameCZ: "test18"}

预期结果19: {id: 18, name: "Transportation and Storage", nameCZ: "test18"}如果语言是英语,并且我们具有选定的值“ Transportation and Storage”,并且如果我更改语言,则希望以某种方式翻译/选择“ test18”

在HTML上,我有:

<div class="field-box">

      <mat-form-field formGroupName="industry" *ngIf="language">
        <input type="text" placeholder="Search for Industries " aria-label="Number" matInput
          formControlName="searchIndustriesInput" [matAutocomplete]="industryAutoComplete">
        <mat-autocomplete #industryAutoComplete="matAutocomplete" [displayWith]="displayIndustries.bind(this)"
          (optionSelected)="industrySelected($event)">
          <div *ngIf="showCurrentLang">
            <mat-option *ngFor="let item of filteredIndustries | async" [value]="item">
              {{item.name}}
            </mat-option>
          </div>
          <div *ngIf="!showCurrentLang">
            <mat-option *ngFor="let item of filteredIndustries | async" [value]="item">
              {{item.nameCZ}}
            </mat-option>
          </div>
        </mat-autocomplete>
        <div
          *ngIf="industryForm.controls.id.invalid && (industryForm.controls.id.dirty || industryForm.controls.id.touched)"
          class="alert alert-danger">
          <mat-error *ngIf="industryForm.controls.id.errors.required">Must fill this field</mat-error>
        </div>
      </mat-form-field>
    </div>
  </div>

并且在 TS 我有

export class CustomerQuestionnaireComponent implements OnInit {
  selectedValueEmployeeValue: string;
  selectedValueIndustryValue: string;
  selectedValueLanguageValue: string;
  selectedValueAppsValue: string;
  show: boolean;
  showCurrentLang: boolean;
  private language: string;
  afterDisplayIndustries: boolean;
  filteredIndustries: Observable<IIndustry[]>;
  selectedApps: IAppIntegratedApp[] = [];

  @ViewChildren(MatChip) children: QueryList<MatChip>;

  form: FormGroup;

  @Input() isLoading: boolean;
  @Input() industries: IIndustry[];
  @Input() errMsg: string;
  @Input() updateMsg: string;
  @Input() customerPreference: CustomerPreference;
  @Input() avaliableLanguages: ILanguage[];
  @Input() filteredApps: IAppIntegratedApp[];

  @Output() searchApps: EventEmitter<string> = new EventEmitter<string>();

  @ViewChild('auto') matAutocomplete: MatAutocomplete;
  @ViewChild('searchAppInput') searchAppInput: ElementRef;

  companySizeValues: IDataSourceOne[] = [
    { key: 'INDIVIDUAL', value: 'Individual(1)' },
    { key: 'MICRO', value: 'Micro(2-9)' },
    { key: 'SMALL', value: 'Small(10-49)' },
    { key: 'MEDIUM', value: 'Medium-sized(49-249)' },
    { key: 'BIG', value: 'Big(250+)' },
  ];

  separatorKeysCodes: number[] = [ENTER, COMMA];

  constructor(private fb: FormBuilder, private langService: LangService ,
              private translate: TranslateService) {
    this.langService.currentLang.subscribe((lang) => {
      this.language = lang;
      if (this.language === 'en') {
        this.showCurrentLang = true ;
      } else {
        this.showCurrentLang = false ;
      }
      if (this.afterDisplayIndustries) {
        this.displayIndustries((<FormGroup>this.form.controls.industry).value.searchIndustriesInput);
        this.industrySelected();
      }
    });

  }
  get isFormReady() {
    return this.avaliableLanguages !== undefined;
  }

  ngOnInit() {
    this.buildForm();
    this.toggleOtherIndustryField();

    this.filteredIndustries = (<FormGroup>this.form.controls.industry).controls.searchIndustriesInput.valueChanges
      .pipe(
        startWith(''),
        map(value => this.filter(value)),
      );
  }

  private filter (value: string | IIndustry): IIndustry[] {
    if (this.language === 'en') {
      console.log(this.language);
      if (value && (<IIndustry>value).name) {
        return this.industries;
      }

      const filterValue = (<string>value).toLowerCase();

      return this.industries.filter(option => option.name.toLowerCase().includes(filterValue));
    }

    if (value && (<IIndustry>value).nameCZ) {
      return this.industries;
    }

    const filterValue = (<string>value).toLowerCase();

    return this.industries.filter(option => option.nameCZ.toLowerCase().includes(filterValue));

  }

  displayIndustries (industry: IIndustry) {
    if  (industry) {
      this.afterDisplayIndustries = true;
      console.log((this.language === 'en') ? industry.name : industry.nameCZ);
      return (this.language === 'en') ? industry.name : industry.nameCZ;
    }
    return undefined;
  }

  buildForm(): void {
    this.form = this.fb.group({
      industry: this.fb.group({
        searchIndustriesInput: this.customerPreference.industry,
        id: [this.customerPreference.industry.id, [
          Validators.required,
        ]],
      });



  }





  get industryForm(): FormGroup {
    return this.f.industry as FormGroup;
  }



  get f() {
    return this.form.controls;
  }

  industrySelected(e?) {
    const industryForm = <FormGroup>this.form.controls.industry;
    industryForm.controls.id.setValue(industryForm.controls.searchIndustriesInput.value.id);
    this.toggleOtherIndustryField();
  }


}

请问有什么人可以帮助我..提前致谢。

1 个答案:

答案 0 :(得分:1)

一个简单的*ngIf会为您完成工作,请记住,当我们选择一个选项时,我们是在数组中选择一个项目-英语或捷克语描述是特定项目的子代;为了显示完整的演示,我在顶部插入了一个单选按钮,以在两种语言之间切换...

相关的 HTML

<mat-radio-group aria-label="Select an option" [(ngModel)]="selectedLanguage">
    <mat-radio-button value="english">English</mat-radio-button>
    <mat-radio-button value="czech">Czech</mat-radio-button>
</mat-radio-group>
<br/>
<p> selected language: {{selectedLanguage}} </p>
<br/>

<mat-form-field>
  <mat-label>select option</mat-label>
  <mat-select [formControl]="langSelect">
    <mat-option *ngFor="let item of dualArray" [(value)]="item">
      <!-- {{item.id}} -->
      <ng-container *ngIf="selectedLanguage == 'english'">
        {{item.name}}
      </ng-container>
      <ng-container *ngIf="selectedLanguage == 'czech'">
        {{item.nameCZ}}
      </ng-container>
    </mat-option>
  </mat-select>
</mat-form-field>
<p>You selected:
  <ng-container *ngIf="selectedLanguage == 'english'">
    {{langSelect.value?.name}}
  </ng-container>
  <ng-container *ngIf="selectedLanguage == 'czech'">
    {{langSelect.value?.nameCZ}}
  </ng-container>
</p>

相关的 TS

import { Component } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';

/** @title Select with 2-way value binding */
@Component({
  selector: 'select-value-binding-example',
  templateUrl: 'select-value-binding-example.html',
  styleUrls: ['select-value-binding-example.css'],
})
export class SelectValueBindingExample {
  selected = '';
  selectedLanguage = 'english';
  langSelect = new FormControl('', []);
  dualArray = [
    { id: 19, name: "Travel Recreation and Leisure", nameCZ: "test19" }
    , { id: 20, name: "Wholesale and Distribution", nameCZ: "test20" }
    , { id: 1, name: "Agriculture and Mining", nameCZ: "test1", description: "hello" }
    , { id: 2, name: "Business Services", nameCZ: "test2" }
    , { id: 3, name: "Computer and Electronics", nameCZ: "test3" }
    , { id: 4, name: "Consumer Services", nameCZ: "test4" }
    , { id: 5, name: "Education", nameCZ: "test5" }
    , { id: 6, name: "Energy and Utilities", nameCZ: "test 6" }
    , { id: 7, name: "Financial Services", nameCZ: "test 7" }
    , { id: 8, name: "Government", nameCZ: "test 8" }
    , { id: 9, name: "Health, Pharmaceuticals, and Biotech", nameCZ: "test9" }
    , { id: 10, name: "Manufacturing", nameCZ: "test10" }
    , { id: 11, name: "Media and Entertainment", nameCZ: "test11" }
    , { id: 12, name: "Non-profit", nameCZ: "test12" }
    , { id: 13, name: "Other", nameCZ: "test13" }
    , { id: 14, name: "Real Estate and Construction", nameCZ: "test14" }
    , { id: 15, name: "Retail", nameCZ: "test15" }
    , { id: 16, name: "Software and Internet", nameCZ: "test16" }
    , { id: 17, name: "Telecommunications", nameCZ: "test17" }
    , { id: 18, name: "Transportation and Storage", nameCZ: "test18" }
  ];
}

完成working stackblitz here