Aggiungere interattività negli oggetti visivi tramite le selezioni degli oggetti visivi di Power BIAdd interactivity into visual by Power BI visuals selections
Power BI offre due modi di interazione tra gli oggetti visivi: la selezione e il filtro.Power BI provides two ways of interaction between visuals - selection and filtering. Nell'esempio seguente viene illustrato come selezionare qualsiasi elemento in un oggetto visivo e inviare una notifica agli altri oggetti visivi nel report sul nuovo stato di selezione.The sample below demonstrates how to select any items in one visual and notify other visuals in the report about new selection state.
L'oggetto Selection
corrisponde all'interfaccia:Selection
object corresponds to the interface:
export interface ISelectionId {
equals(other: ISelectionId): boolean;
includes(other: ISelectionId, ignoreHighlight?: boolean): boolean;
getKey(): string;
getSelector(): Selector;
getSelectorsByColumn(): SelectorsByColumn;
hasIdentity(): boolean;
}
Come usare SelectionManager per selezionare i punti datiHow to use SelectionManager to select data points
L'oggetto host dell'oggetto visivo fornisce il metodo per la creazione di un'istanza di gestione selezione.The visual host object provides the method for creating an instance of selection manager. La gestione selezione è responsabile di selezionare, annullare la selezione, visualizzare il menu di scelta rapida, archiviare le selezioni correnti e verificare lo stato della selezione.The selection manager responsible to select, to clear selection, to show the context menu, to store current selections and check selection state. La gestione selezione ha anche i metodi corrispondenti per queste azioni.And the selection manager has corresponded methods for those actions.
Creare un'istanza della gestione selezioneCreate an instance of the selection manager
Per usare la gestione selezione è necessario creare la relativa istanza.For using the selection manager, you need to create the instance of a selection manager. Gli oggetti visivi creano in genere un'istanza di gestione selezione nell'elemento constructor
dell'oggetto visivo.Usually, visuals create a selection manager instance in the constructor
of the visual object.
export class Visual implements IVisual {
private target: HTMLElement;
private host: IVisualHost;
private selectionManager: ISelectionManager;
// ...
constructor(options: VisualConstructorOptions) {
this.host = options.host;
// ...
this.selectionManager = this.host.createSelectionManager();
}
// ...
}
Creare un'istanza del generatore di selezioneCreate an instance of the selection builder
Quando viene creata l'istanza di gestione selezione, è necessario creare selections
per ogni punto dati dell'oggetto visivo.When the selection manager instance is created, you need to create selections
for each data point of the visual. L'oggetto host dell'oggetto visivo offre il metodo createSelectionIdBuilder
per generare la selezione per ogni punto dati.The visual host object provides createSelectionIdBuilder
method to generate selection for each data point. Questo metodo restituisce l'istanza dell'oggetto con l'interfaccia powerbi.visuals.ISelectionIdBuilder
:This method return instance of the object with interface powerbi.visuals.ISelectionIdBuilder
:
export interface ISelectionIdBuilder {
withCategory(categoryColumn: DataViewCategoryColumn, index: number): this;
withSeries(seriesColumn: DataViewValueColumns, valueColumn: DataViewValueColumn | DataViewValueColumnGroup): this;
withMeasure(measureId: string): this;
withMatrixNode(matrixNode: DataViewMatrixNode, levels: DataViewHierarchyLevel[]): this;
withTable(table: DataViewTable, rowIndex: number): this;
createSelectionId(): ISelectionId;
}
Questo oggetto ha metodi corrispondenti per creare selections
per diversi tipi di mapping di visualizzazione dati.This object has corresponded methods to create selections
for different types of data view mappings.
Nota
I metodi withTable
e withMatrixNode
sono stati introdotti nell'API 2.5.0 degli oggetti visivi di Power BI.The methods withTable
and withMatrixNode
were introduced on API 2.5.0 of the Power BI visuals.
Se è necessario usare le selezioni per i mapping di visualizzazione dati di tabella o di matrice, è necessario aggiornare l'API alla versione 2.5.0 o successiva.If you need to use selections for table or matrix data view mappings you need to update API version to 2.5.0 or higher.
Creare selezioni per il mapping di visualizzazione dati categoricaCreate selections for categorical data view mapping
Esaminiamo il modo in cui le selezioni vengono rappresentate nel mapping di visualizzazione dati categorica per il set di dati di esempio:Let's review how selections represent on categorical data view mapping for sample dataset:
ProduttoreManufacturer | TypeType | valoreValue |
---|---|---|
ChryslerChrysler | Domestic CarDomestic Car | 2888328883 |
ChryslerChrysler | Domestic TruckDomestic Truck | 117131117131 |
ChryslerChrysler | Import CarImport Car | 00 |
ChryslerChrysler | Import TruckImport Truck | 63626362 |
FordFord | Domestic CarDomestic Car | 5003250032 |
FordFord | Domestic TruckDomestic Truck | 122446122446 |
FordFord | Import CarImport Car | 00 |
FordFord | Import TruckImport Truck | 00 |
GMGM | Domestic CarDomestic Car | 6542665426 |
GMGM | Domestic TruckDomestic Truck | 138122138122 |
GMGM | Import CarImport Car | 197197 |
GMGM | Import TruckImport Truck | 00 |
HondaHonda | Domestic CarDomestic Car | 5145051450 |
HondaHonda | Domestic TruckDomestic Truck | 4611546115 |
HondaHonda | Import CarImport Car | 29322932 |
HondaHonda | Import TruckImport Truck | 00 |
NissanNissan | Domestic CarDomestic Car | 5147651476 |
NissanNissan | Domestic TruckDomestic Truck | 4734347343 |
NissanNissan | Import CarImport Car | 54855485 |
NissanNissan | Import TruckImport Truck | 14301430 |
ToyotaToyota | Domestic CarDomestic Car | 5564355643 |
ToyotaToyota | Domestic TruckDomestic Truck | 6122761227 |
ToyotaToyota | Import CarImport Car | 2079920799 |
ToyotaToyota | Import TruckImport Truck | 2361423614 |
L'oggetto visivo usa il mapping di visualizzazione dati seguente:And the visual uses the following data view mapping:
{
"dataRoles": [
{
"displayName": "Columns",
"name": "columns",
"kind": "Grouping"
},
{
"displayName": "Rows",
"name": "rows",
"kind": "Grouping"
},
{
"displayName": "Values",
"name": "values",
"kind": "Measure"
}
],
"dataViewMappings": [
{
"categorical": {
"categories": {
"for": {
"in": "columns"
}
},
"values": {
"group": {
"by": "rows",
"select": [
{
"for": {
"in": "values"
}
}
]
}
}
}
}
]
}
Nell'esempio Manufacturer
è columns
e Type
è rows
.In the sample, Manufacturer
is columns
and Type
is rows
. Sono presenti serie create da valori di raggruppamenti per rows
(Type
).There's series created by groupings values by rows
(Type
).
L'oggetto visivo può anche filtrare i dati per Manufacturer
e Type
.And visual should able to slice data by Manufacturer
and Type
too.
Quando ad esempio l'utente seleziona Chrysler
per Manufacturer
, gli altri oggetti visivi visualizzano i dati seguenti:For example, when user selects Chrysler
by Manufacturer
, other visuals should show following data:
ProduttoreManufacturer | TypeType | valoreValue |
---|---|---|
ChryslerChrysler | Domestic CarDomestic Car | 2888328883 |
ChryslerChrysler | Domestic TruckDomestic Truck | 117131117131 |
ChryslerChrysler | Import CarImport Car | 00 |
ChryslerChrysler | Import TruckImport Truck | 63626362 |
Quando l'utente seleziona Import Car
per Type
(seleziona i dati in base alla serie), gli altri oggetti visivi visualizzano i dati seguenti:When user selects Import Car
by Type
(selects data by series), other visuals should show following data:
ProduttoreManufacturer | TypeType | valoreValue |
---|---|---|
ChryslerChrysler | Import CarImport Car | 00 |
FordFord | Import CarImport Car | 00 |
GMGM | Import CarImport Car | 197197 |
HondaHonda | Import CarImport Car | 29322932 |
NissanNissan | Import CarImport Car | 54855485 |
ToyotaToyota | Import CarImport Car | 2079920799 |
È necessario compilare i carrelli dati degli oggetti visivi.Need to fill the visual data baskets.
Sono presenti Manufacturer
come categoria (colonne), Type
come serie (righe) e Value
come Values
per le serie.There are Manufacturer
as category (columns), Type
as series (rows) and Value
as Values
for series.
Nota
Gli elementi Values
sono necessari per le serie perché in base al mapping di visualizzazione dati l'oggetto visivo prevede che Values
verrà raggruppato in base ai dati Rows
.The Values
are required for series because according to data view mapping the visual expects that Values
will be grouped by Rows
data.
Creare selezioni per le categorieCreate selections for categories
// categories
const categories = dataView.categorical.categories;
// create label for 'Manufacturer' column
const p = document.createElement("p") as HTMLParagraphElement;
p.innerText = categories[0].source.displayName.toString();
this.target.appendChild(p);
// get count of category elements
const categoriesCount = categories[0].values.length;
// iterate all categories to generate selection and create button elements to use selections
for (let categoryIndex = 0; categoryIndex < categoriesCount; categoryIndex++) {
const categoryValue: powerbi.PrimitiveValue = categories[0].values[categoryIndex];
const categorySelectionId = this.host.createSelectionIdBuilder()
.withCategory(categories[0], categoryIndex) // we have only one category (only one `Manufacturer` column)
.createSelectionId();
this.dataPoints.push({
value: categoryValue,
selection: categorySelectionId
});
console.log(categorySelectionId);
// create button element to apply selection on click
const button = document.createElement("button") as HTMLButtonElement;
button.value = categoryValue.toString();
button.innerText = categoryValue.toString();
button.addEventListener("click", () => {
// handle click event to apply correspond selection
this.selectionManager.select(categorySelectionId);
});
this.target.appendChild(button);
}
Nel codice di esempio si può osservare che viene eseguita l'iterazione di tutte le categorie.In the sample code, you can see that we iterate all categories. In ogni iterazione viene chiamato il metodo createSelectionIdBuilder
per creare la selezione successiva per ogni categoria chiamando il metodo withCategory
del generatore di selezione.And in each iteration, we call createSelectionIdBuilder
to create the next selection for each category by calling withCategory
method of the selection builder. Il metodo createSelectionId
viene usato come metodo finale per restituire l'oggetto selection
generato.The method createSelectionId
is used as a final method to return the generated selection
object.
Nel metodo withCategory
viene passata la colonna di category
. Nell'esempio si tratta di Manufacturer
e dell'indice dell'elemento categoria.In withCategory
method, we pass the column of category
, in the sample, it's Manufacturer
and index of category element.
Creare selezioni per le serieCreate selections for series
// get groupped values for series
const series: powerbi.DataViewValueColumnGroup[] = dataView.categorical.values.grouped();
// create label for 'Type' column
const p2 = document.createElement("p") as HTMLParagraphElement;
p2.innerText = dataView.categorical.values.source.displayName;
this.target.appendChild(p2);
// iterate all series to generate selection and create button elements to use selections
series.forEach( (ser: powerbi.DataViewValueColumnGroup) => {
// create selection id for series
const seriesSelectionId = this.host.createSelectionIdBuilder()
.withSeries(dataView.categorical.values, ser)
.createSelectionId();
this.dataPoints.push({
value: ser.name,
selection: seriesSelectionId
});
// create button element to apply selection on click
const button = document.createElement("button") as HTMLButtonElement;
button.value =ser.name.toString();
button.innerText = ser.name.toString();
button.addEventListener("click", () => {
// handle click event to apply correspond selection
this.selectionManager.select(seriesSelectionId);
});
this.target.appendChild(button);
});
Creare selezioni per il mapping di visualizzazione dati di tabellaCreate selections for table data view mapping
Esempio di mapping di visualizzazione dati di tabellaSample of table data views mapping
{
"dataRoles": [
{
"displayName": "Values",
"name": "values",
"kind": "GroupingOrMeasure"
}
],
"dataViewMappings": [
{
"table": {
"rows": {
"for": {
"in": "values"
}
}
}
}
]
}
Per creare una selezione per ogni riga del mapping di visualizzazione dati di tabella, è necessario chiamare il metodo withTable
del generatore di selezione.To create a selection for each row of table data view mapping, you need to call withTable
method of selection builder.
public update(options: VisualUpdateOptions) {
const dataView = options.dataViews[0];
dataView.table.rows.forEach((row: DataViewTableRow, rowIndex: number) => {
this.target.appendChild(rowDiv);
const selection: ISelectionId = this.host.createSelectionIdBuilder()
.withTable(dataView.table, rowIndex)
.createSelectionId();
}
}
Il codice visivo esegue l'iterazione delle righe della tabella e ogni riga chiama il metodo tabella withTable
.The visual code iterates the rows of the table and each row calls withTable
table method. I parametri del metodo withTable
sono l'oggetto table
e l'indice della riga della tabella.Parameters of withTable
method are table
object and index of the table row.
Creare selezioni per il mapping di visualizzazione dati di matriceCreate selections for matrix data view mapping
public update(options: VisualUpdateOptions) {
const host = this.host;
const rowLevels: powerbi.DataViewHierarchyLevel[] = dataView.matrix.rows.levels;
const columnLevels: powerbi.DataViewHierarchyLevel[] = dataView.matrix.rows.levels;
// iterate rows hierarchy
nodeWalker(dataView.matrix.rows.root, rowLevels);
// iterate columns hierarchy
nodeWalker(dataView.matrix.columns.root, columnLevels);
function nodeWalker(node: powerbi.DataViewMatrixNode, levels: powerbi.DataViewHierarchyLevel[]) {
const nodeSelection = host.createSelectionIdBuilder().withMatrixNode(node, levels);
if (node.children && node.children.length) {
node.children.forEach(child => {
nodeWalker(child, levels);
});
}
}
}
Nell'esempio nodeWalker
esegue chiamate in modo ricorsivo per ogni nodo e nodo figlio.In the sample, nodeWalker
calls recursively for each node and child nodes.
nodeWalker
crea l'oggetto nodeSelection
a ogni chiamata.nodeWalker
creates nodeSelection
object on each call. Ogni nodeSelection
rappresenta l'elemento selection
dei nodi corrispondenti.And each nodeSelection
represent selection
of correspond nodes.
Selezionare i punti dati per filtrare altri oggetti visiviSelect datapoints to slice other visuals
Nei codici di esempio delle selezioni per il mapping di visualizzazione dati categorica è stato creato un gestore degli eventi clic per gli elementi pulsante.In the sample, codes of selections for categorical data view mapping, you saw that we created a click handler for button elements. Il gestore chiama il metodo select
di gestione selezione e passa l'oggetto di selezione.The handler calls select
method of the selection manager and passes the selection object.
button.addEventListener("click", () => {
// handle click event to apply correspond selection
this.selectionManager.select(categorySelectionId);
});
L'interfaccia del metodo select
èThe interface of select
method is
interface ISelectionManager {
// ...
select(selectionId: ISelectionId | ISelectionId[], multiSelect?: boolean): IPromise<ISelectionId[]>;
// ...
}
Si noti che select
può accettare una matrice di selezioni.You can see select
can accept an array of selections. Ciò significa che l'oggetto visivo può selezionare diversi punti dati.It means your visual can select several datapoints. Il secondo parametro multiSelect
è responsabile della selezione multipla.The second parameter multiSelect
responsible for multi-select. Se il valore è True, Power BI non annulla lo stato della selezione precedente e applica la selezione corrente. In caso contrario, viene ripristinata la selezione precedente.If the value is true, Power BI doesn't clear the previous selection state and apply current selection otherwise previous selection will reset.
Scenario tipico dell'uso di multiSelect
per la gestione dello stato del pulsante CTRL su un evento clic.The typical scenario of using multiSelect
handling CTRL button state on click event.
button.addEventListener("click", (mouseEvent) => {
const multiSelect = (mouseEvent as MouseEvent).ctrlKey;
this.selectionManager.select(seriesSelectionId, multiSelect);
});