【问题标题】:how to set 2 to 3 values default in Dropdownlist如何在下拉列表中设置 2 到 3 个默认值
【发布时间】:2019-07-06 20:18:41
【问题描述】:

在此代码中,如何在下拉列表中将 2 个值设置为默认值,当我刷新页面时,应将最后 2 个选定值设置为默认值 提前致谢

https://stackblitz.com/edit/angular-ku2by4-mgaqtp

【问题讨论】:

    标签: html angular typescript angular7


    【解决方案1】:

    您可以使用 localStorage 来存储一个人选择的多个值......当我们刷新页面时,这些值是从构造函数中的 localStorage 中获取的。

    您可以通过以下 2 项更改来更新您的 stackblitz 以查看效果...

    select-multiple-example.ts

    import {Component} from '@angular/core';
    import {FormControl} from '@angular/forms';
    
    /** @title Select with multiple selection */
    @Component({
      selector: 'select-multiple-example',
      templateUrl: 'select-multiple-example.html',
      styleUrls: ['select-multiple-example.css'],
    })
    export class SelectMultipleExample {
      toppings = new FormControl();
      toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];
      selected:string[]; //= ['Mushroom', 'Onion'];
      previousSelection:string[];
    
      constructor(){
        this.selected = [];
        this.previousSelection = [];
        var readStore = localStorage.getItem('selected');
    
        if (readStore.length>0){
          this.previousSelection = readStore.split(",");
        }
    
        if (this.previousSelection.length>0){
          for(var i=0; i<this.previousSelection.length; i++){
            this.selected.push(this.previousSelection[i]) ; 
          }
        }
      }
    
      selectionChanged(passedVal){
        while(this.selected.length>2){
          this.selected.shift();
        }
    
        var combinedString = this.selected.join();
        localStorage.setItem('selected', combinedString);
      }
    
    }
    

    select-multiple-example.html

       Previous selection: <b>{{previousSelection}}</b> <br/> 
    2 Valid selections: <b>{{selected}}</b><br/>
    <br/>
    <mat-form-field>
      <mat-select placeholder="Toppings" [formControl]="toppings" multiple [(ngModel)]="selected" (selectionChange)="selectionChanged($event.value)">
    <mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
      </mat-select>
    </mat-form-field>

    更新:尽管用户尝试选择超过 2 个选项,但用户要求只选择 2 个选项 - 更新代码以反映这一点;但是,有一个open issue 在更新 ngModel 时,mat-select 选项不会更新;这就是为什么用户可以选择 2 个以上的多个选项,但只有 2 个选项(我们也显示在屏幕上)会继续前进。

    UPDATE #2(用于材料表): 将现有的 table-basic-example.html 替换为:

    <div class="example-container mat-elevation-z8">
      <mat-table #table [dataSource]="dataSource">
    
        <!--- Note that these columns can be defined in any order.
              The actual rendered columns are set as a property on the row definition" -->
    
        <!-- Position Column -->
        <ng-container matColumnDef="checked">
          <mat-header-cell *matHeaderCellDef>Check</mat-header-cell>
          <mat-cell *matCellDef="let element">
            <mat-checkbox [(ngModel)]="element.checked" (click)="selectionChanged(element)"></mat-checkbox>
          </mat-cell>
        </ng-container>
    
        <!-- Position Column -->
        <ng-container matColumnDef="position">
          <mat-header-cell *matHeaderCellDef> No. </mat-header-cell>
          <mat-cell *matCellDef="let element"> {{element.position}} </mat-cell>
        </ng-container>
    
        <!-- Name Column -->
        <ng-container matColumnDef="name">
          <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
          <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
        </ng-container>
    
        <!-- Weight Column -->
        <ng-container matColumnDef="weight">
          <mat-header-cell *matHeaderCellDef> Weight </mat-header-cell>
          <mat-cell *matCellDef="let element"> {{element.weight}} </mat-cell>
        </ng-container>
    
        <!-- Symbol Column -->
        <ng-container matColumnDef="symbol">
          <mat-header-cell *matHeaderCellDef> Symbol </mat-header-cell>
          <mat-cell *matCellDef="let element"> {{element.symbol}} </mat-cell>
        </ng-container>
    
        <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
        <mat-row *matRowDef="let row; columns: displayedColumns;" [ngClass]="{hovered: row.hovered, highlighted: row.highlighted}" (click)="row.highlighted = !row.highlighted" (mouseover)="row.hovered = true" (mouseout)="row.hovered = false"></mat-row>
      </mat-table>
    </div>
    
    <hr/>
    <div *ngFor="let item of selectedCells">
      {{item.position}} - {{item.name}}
    </div>
    
    <!-- Copyright 2018 Google Inc. All Rights Reserved.
        Use of this source code is governed by an MIT-style license that
        can be found in the LICENSE file at http://angular.io/license -->

    将现有的 table-basic-example.ts 替换为:

    import { Component } from '@angular/core';
    
    /**
     * @title Basic table
     */
    @Component({
      selector: 'table-basic-example',
      styleUrls: ['table-basic-example.css'],
      templateUrl: 'table-basic-example.html',
    })
    export class TableBasicExample {
      displayedColumns = ['checked', 'position', 'name', 'weight', 'symbol'];
      dataSource = ELEMENT_DATA;
      selectedCells:Element[] = [];
    
      // highlight(element: Element) {    element.highlighted = !element.highlighted;  }
    
    
      selectionChanged(val: Element){
        console.log(val);
        if(!val.checked){
          if (this.selectedCells.length <2){
            /* just insert new entry */
            var duplicateCheck = false;
            for(var j=0; j<this.selectedCells.length;j++){
              if (this.selectedCells[j].position == val.position ){
                duplicateCheck = true;
              }
            }
            if(!duplicateCheck){
              this.selectedCells.push(val);
            }
          } else {
            for(var j=0; j<this.selectedCells.length;j++){
              if (this.selectedCells[j].position == val.position ){
                duplicateCheck = true;
              }
            }
            if(!duplicateCheck){
              this.selectedCells.push(val);
              /* remove the oldest entry  - and insert new entry */
              for(var i=0; i<this.dataSource.length; i++){
                if(this.dataSource[i].position == this.selectedCells[0].position){
                  //console.log("about to remove",this.selectedCells[0].position);
                  this.dataSource[i].checked = false;
                }
              }
              this.selectedCells.shift();
              //console.log(this.dataSource);
            }
    
          }
        }
      }
    }
    
    export interface Element {
      checked: boolean;
      name: string;
      position: number;
      weight: number;
      symbol: string;
      highlighted?: boolean;
      hovered?: boolean;
    }
    
    const ELEMENT_DATA: Element[] = [
      { checked: false, position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
      { checked: false, position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
      { checked: false, position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' },
      { checked: false, position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' },
      { checked: false, position: 5, name: 'Boron', weight: 10.811, symbol: 'B' },
      { checked: false, position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C' },
      { checked: false, position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N' },
      { checked: false, position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O' },
      { checked: false, position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F' },
      { checked: false, position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne' },
      { checked: false, position: 11, name: 'Sodium', weight: 22.9897, symbol: 'Na' },
      { checked: false, position: 12, name: 'Magnesium', weight: 24.305, symbol: 'Mg' },
      { checked: false, position: 13, name: 'Aluminum', weight: 26.9815, symbol: 'Al' },
      { checked: false, position: 14, name: 'Silicon', weight: 28.0855, symbol: 'Si' },
      { checked: false, position: 15, name: 'Phosphorus', weight: 30.9738, symbol: 'P' },
      { checked: false, position: 16, name: 'Sulfur', weight: 32.065, symbol: 'S' },
      { checked: false, position: 17, name: 'Chlorine', weight: 35.453, symbol: 'Cl' },
      { checked: false, position: 18, name: 'Argon', weight: 39.948, symbol: 'Ar' },
      { checked: false, position: 19, name: 'Potassium', weight: 39.0983, symbol: 'K' },
      { checked: false, position: 20, name: 'Calcium', weight: 40.078, symbol: 'Ca' },
    ];
    
    
    /**  Copyright 2018 Google Inc. All Rights Reserved.
        Use of this source code is governed by an MIT-style license that
        can be found in the LICENSE file at http://angular.io/license */
    

    【讨论】:

    • @pradeepM,这对你有用吗?我刚刚检查了您创建的新 stackblitz...
    • (上面的链接)这里被限制为 2 个 chekcbox,但是当我点击第三个复选框时,我需要之前的任何一个复选框都应该取消选中,如果可能的话,你能帮我吗
    • 你只是扩大了你的问题范围...... :)...... 给我一些时间来帮助
    • 已选择:字符串[]; //= ['蘑菇', '洋葱'];如果数据来自网络服务如何传递数据
    • 创建一个进行http调用的服务,从你的组件中调用这个服务并将来自服务的数据插入到toppingList
    猜你喜欢
    • 2017-05-28
    • 2016-09-16
    • 1970-01-01
    • 2014-07-19
    • 2014-10-20
    • 1970-01-01
    • 2020-07-06
    • 2013-10-23
    • 1970-01-01
    相关资源
    最近更新 更多