如何在Angular 4的两个mat-select中实现对象数组联动检索
我来帮你搞定这个Angular Material的联动下拉需求!其实核心就是通过绑定第一个下拉框的选中值,动态给第二个下拉框提供数据源,咱们一步步来:
1. 组件类(.ts文件)的准备工作
首先在你的组件里定义好数据源,以及用来存储选中项和动态notes的变量:
import { Component } from '@angular/core'; @Component({ selector: 'app-person-notes-select', templateUrl: './person-notes-select.component.html', styleUrls: ['./person-notes-select.component.css'] }) export class PersonNotesSelectComponent { // 你的原始person数组,直接用你提供的示例数据 persons = [ { "id": 0, name: "aa", notes: [{ "id": 0, "xx": 14 }, { "id": 1, "xx": 12 }, { "id": 1, "zz": 9 }] }, { "id": 2, name: "bb", notes: [{ "id": 0, "xx": "7" }, { "id": 1, "xx": 17 }] }, { "id": 3, name: "cc", notes: [{ "id": 0, "xx": 18 }] } ]; // 存储选中的person对象 selectedPerson: any; // 存储当前选中person对应的notes列表 currentNotes: any[] = []; // 当选中的person变化时,更新notes列表 onPersonChange() { // 如果选中了person,就把它的notes赋值给currentNotes;没选中就清空 this.currentNotes = this.selectedPerson ? [...this.selectedPerson.notes] : []; // 可选:如果需要对notes按id去重,用下面这段替换上面的赋值 // if (this.selectedPerson) { // const uniqueNotes = Array.from( // new Map(this.selectedPerson.notes.map(note => [note.id, note])).values() // ); // this.currentNotes = uniqueNotes; // } else { // this.currentNotes = []; // } } }
2. 模板文件(.html)的写法
接下来写页面模板,实现两个联动的mat-select:
<!-- 第一个下拉框:选择Person --> <mat-form-field appearance="fill"> <mat-label>选择Person</mat-label> <mat-select [(ngModel)]="selectedPerson" (selectionChange)="onPersonChange()"> <mat-option *ngFor="let person of persons" [value]="person"> {{ person.name }} (ID: {{ person.id }}) </mat-option> </mat-select> </mat-form-field> <!-- 第二个下拉框:根据选中的Person动态显示Notes --> <mat-form-field appearance="fill" *ngIf="currentNotes.length > 0"> <mat-label>选择Note</mat-label> <mat-select> <mat-option *ngFor="let note of currentNotes; let i = index" [value]="note"> <!-- 灵活显示note的所有属性,不管是xx还是zz --> 序号{{ i + 1 }} - ID: {{ note.id }} | <span *ngFor="let key of Object.keys(note); let last = last"> {{ key }}: {{ note[key] }} {{ last ? '' : '| ' }} </span> </mat-option> </mat-select> </mat-form-field> <!-- 提示信息:未选中Person或无Notes时显示 --> <p *ngIf="!selectedPerson" style="color: #666;">请先选择一个Person</p> <p *ngIf="selectedPerson && currentNotes.length === 0" style="color: #666;">该Person没有可选择的Notes</p>
3. 必要的模块导入
别忘了在你的功能模块里导入Angular Material和表单相关的模块,否则组件会报错:
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MatSelectModule } from '@angular/material/select'; import { MatFormFieldModule } from '@angular/material/form-field'; import { FormsModule } from '@angular/forms'; import { PersonNotesSelectComponent } from './person-notes-select.component'; @NgModule({ declarations: [PersonNotesSelectComponent], imports: [ CommonModule, MatSelectModule, MatFormFieldModule, FormsModule ], exports: [PersonNotesSelectComponent] }) export class PersonNotesSelectModule { }
这样就能实现你想要的效果:第一个下拉选person,第二个下拉自动加载对应person的notes列表,而且完全绑定对象数据~
内容的提问来源于stack exchange,提问作者Mohamed Letaief
相关产品推荐
相关产品推荐

