У меня есть эта простая сетка:
![enter image description here](https://i.stack.imgur.com/VCwsi.png)
Значения в списке DropCown ChildColumn зависят от того, какую опцию пользователь выбрал в списке DropDown в родительском компоненте.
Например: пользователь выбирает Option2 в родительском столбце.List2 будет отображаться в ChildColumn.
![enter image description here](https://i.stack.imgur.com/rrHKA.png)
Однако для отображения List2 я обновил ChildColumn.Сейчас я делаю это с помощью кнопки «Обновить сетку».Однако я хочу, чтобы это происходило автоматически всякий раз, когда пользователь выбирает новую опцию в ParentColumn.
Я не смог найти способ сделать это.
Вот код grid.component.ts:
import {Component, OnInit} from '@angular/core';
import { FirstCellRendererComponent } from './first-cell-renderer/first-cell-renderer.component';
import { SecondCellRendererComponent } from './second-cell-renderer/second-cell-renderer.component';
import {ParentComChildDropValue} from './parentComChildDropValue.service'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private data: ParentComChildDropValue
) { }
columnDefs = [
{
headerName: "ParentColumn",
field: "prtCol",
cellRenderer:'parentColCellRenderer'
},
{
headerName: "ChildColumn",
field: "chdCol",
cellRenderer: (params) => {
return(
` <select class="form-control">
<br>`
+`<option>` +
this.receivedChosenOptionfromCol1[0]
+`</option>`
+`<option>` +
this.receivedChosenOptionfromCol1[1]
+`</option>` +
`<option>` +
this.receivedChosenOptionfromCol1[2]
+`</option>` +
`<option>` +
this.receivedChosenOptionfromCol1[3]
+`</option>` +
`</select>
`)
}
}
];
rowData = [{}];
frameworkComponents = {
parentColCellRenderer: FirstCellRendererComponent,
childColCellRenderer: SecondCellRendererComponent,
};
receivedChosenOptionfromCol1:string[];
ngOnInit() {
this.data.currentOption.subscribe(receivedOption => (this.receivedChosenOptionfromCol1 = receivedOption));
}
/**THIS CODE IS RESPONSIBLE FOR REFRESHING THE GRID AFTER VALUES HAVE BEEN CHANGED */
private gridApi;
onGridReady(params) {
this.gridApi = params.api;
params.api.sizeColumnsToFit();
}
public refreshCol2() {
const params = { force: true, columns: ["chdCol"] };
this.gridApi.refreshCells(params);
}
}
Вот этот grid.component.html:
<button (click)="refreshCol2()">Refresh grid</button>
<ag-grid-angular
style="width: 500px; height: 500px;"
class="ag-theme-balham"
[enableSorting]="true"
[enableFilter]="true"
[pagination]="true"
[rowData]="rowData"
[columnDefs]="columnDefs"
[frameworkComponents]="frameworkComponents"
(gridReady)="onGridReady($event)"
>
</ag-grid-angular>
Это пользовательская ячейка ParentColumn renderer.ts:
import { Component, OnInit } from '@angular/core';
import {ParentComChildDropValue} from '../parentComChildDropValue.service'
@Component({
selector: 'app-first-cell-renderer',
templateUrl: './first-cell-renderer.component.html',
styleUrls: ['./first-cell-renderer.component.css']
})
export class FirstCellRendererComponent{
/**PS THE FOLLOWING CODE IS CRUCIAL FOR THE CELL RENDERER TO WORK */
params: any;
agInit(params: any): void {
this.params = params;
}
/**!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
/**COMMUNICATION BETWEEN CELL RENDERERS CODE */
constructor(private data: ParentComChildDropValue) { }
/**§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§ */
colTwoList:string[]=[]
public populateListInColTwo(chosenOption){
// I added the following line because without it the colTwoList gets all the accumulated chosen lists
this.colTwoList=[]
console.log('HERE THE CHOSEN OPTION' + chosenOption.value)
if (chosenOption.value==="ParentList_Option1"){
this.colTwoList.push('List1_Option1')
this.colTwoList.push('List1_Option2')
this.colTwoList.push('List1_Option3')
this.colTwoList.push('List1_Option4')
console.log('List One was populated')
}
else if (chosenOption.value==="ParentList_Option2"){
this.colTwoList.push('List2_Option1')
this.colTwoList.push('List2_Option2')
this.colTwoList.push('List2_Option3')
this.colTwoList.push('List2_Option4')
console.log('List Two was populated')
}
else if (chosenOption.value==="ParentList_Option3"){
this.colTwoList.push('List3_Option1')
this.colTwoList.push('List3_Option2')
this.colTwoList.push('List3_Option3')
this.colTwoList.push('List3_Option4')
console.log('List Three was populated')
}
else if (chosenOption.value==="ParentList_Option4"){
this.colTwoList.push('List4_Option1')
this.colTwoList.push('List4_Option2')
this.colTwoList.push('List4_Option3')
this.colTwoList.push('List4_Option4')
console.log('List Four was populated')
}
this.data.changeList(this.colTwoList)
}
}
Это пользовательская ячейка ParentColumn для визуализации html:
<select class="form-control" (change)="populateListInColTwo($event.target)">
<br>
<option id="1"></option>
<option id="1">ParentList_Option1</option>
<option id="2">ParentList_Option2</option>
<option id="3">ParentList_Option3</option>
<option id="4">ParentList_Option4</option>
</select>
Это service.ts, ответственный за отправку данных из пользовательского средства визуализации ячеек ParentColumn в сетку для отображения в childColumn:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class ParentComChildDropValue {
private optionSource = new BehaviorSubject<string[]>([]);
currentOption = this.optionSource.asObservable();
constructor() {}
changeList(receivedOption: string[]) {
this.optionSource.next(receivedOption)
console.log('changeOption works and this is the string list in the service '+receivedOption)
}
}
Я действительно не смог найти способобновить список в ChildColumn всякий раз, когда пользователь выбирает параметр в ParentColumn.У меня уже есть событие, которое запускается всякий раз, когда пользователь выбирает опцию в ParentColumn.Но как я могу использовать это в ChildColumn?
Спасибо!