Adicione interatividade ao visual pelas seleções de visuais do Power BIAdd interactivity into visual by Power BI visuals selections
O Power BI oferece duas maneiras de interação entre visuais: seleção e filtragem.Power BI provides two ways of interaction between visuals - selection and filtering. A amostra abaixo demonstra como selecionar itens em um visual e notificar outros visuais no relatório sobre o novo estado da seleção.The sample below demonstrates how to select any items in one visual and notify other visuals in the report about new selection state.
O objeto Selection
corresponde à interface: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;
}
Como usar o SelectionManager para selecionar pontos de dadosHow to use SelectionManager to select data points
O objeto de host do visual fornece um método para criar a instância do gerenciador de seleção.The visual host object provides the method for creating an instance of selection manager. O gerenciador de seleção responsável por selecionar, limpar a seleção, mostrar o menu de contexto, armazenar as seleções atuais e verificar o estado da seleção.The selection manager responsible to select, to clear selection, to show the context menu, to store current selections and check selection state. E o gerenciador de seleção tem métodos correspondentes para essas ações.And the selection manager has corresponded methods for those actions.
Criar instância do gerenciador de seleçãoCreate an instance of the selection manager
Para usar o gerenciador de seleção, você precisa criar a instância do gerenciador de seleção.For using the selection manager, you need to create the instance of a selection manager. Geralmente, os visuais criam uma instância do gerenciador de seleção em constructor
do objeto visual.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();
}
// ...
}
Criar instância do construtor de seleçãoCreate an instance of the selection builder
Quando a instância do gerenciador de seleção é criada, você precisa criar selections
para cada ponto de dados do visual.When the selection manager instance is created, you need to create selections
for each data point of the visual. O objeto de host do visual fornece o método createSelectionIdBuilder
para gerar seleção para cada ponto de dados.The visual host object provides createSelectionIdBuilder
method to generate selection for each data point. Esse método retorna a instância do objeto com a interface 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;
}
Esse objeto tem métodos correspondentes para criar selections
para diferentes tipos de mapeamentos de exibição de dados.This object has corresponded methods to create selections
for different types of data view mappings.
Observação
Os métodos withTable
e withMatrixNode
foram introduzidos na API 2.5.0 dos visuais do Power BI.The methods withTable
and withMatrixNode
were introduced on API 2.5.0 of the Power BI visuals.
Se você precisar usar seleções para mapeamentos de exibição de dados de tabela ou matriz, precisará atualizar a versão da API para 2.5.0 ou superior.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.
Criar seleções para o mapeamento da exibição de dados categóricosCreate selections for categorical data view mapping
Vamos examinar como as seleções são representadas no mapeamento de exibição de dados categóricos para o conjunto de dados de amostra:Let's review how selections represent on categorical data view mapping for sample dataset:
FabricanteManufacturer | TipoType | ValorValue |
---|---|---|
ChryslerChrysler | Carro nacionalDomestic Car | 2888328883 |
ChryslerChrysler | Caminhonete nacionalDomestic Truck | 117131117131 |
ChryslerChrysler | Carro importadoImport Car | 00 |
ChryslerChrysler | Caminhonete importadaImport Truck | 63626362 |
FordFord | Carro nacionalDomestic Car | 5003250032 |
FordFord | Caminhonete nacionalDomestic Truck | 122446122446 |
FordFord | Carro importadoImport Car | 00 |
FordFord | Caminhonete importadaImport Truck | 00 |
GMGM | Carro nacionalDomestic Car | 6542665426 |
GMGM | Caminhonete nacionalDomestic Truck | 138122138122 |
GMGM | Carro importadoImport Car | 197197 |
GMGM | Caminhonete importadaImport Truck | 00 |
HondaHonda | Carro nacionalDomestic Car | 5145051450 |
HondaHonda | Caminhonete nacionalDomestic Truck | 4611546115 |
HondaHonda | Carro importadoImport Car | 29322932 |
HondaHonda | Caminhonete importadaImport Truck | 00 |
NissanNissan | Carro nacionalDomestic Car | 5147651476 |
NissanNissan | Caminhonete nacionalDomestic Truck | 4734347343 |
NissanNissan | Carro importadoImport Car | 54855485 |
NissanNissan | Caminhonete importadaImport Truck | 14301430 |
ToyotaToyota | Carro nacionalDomestic Car | 5564355643 |
ToyotaToyota | Caminhonete nacionalDomestic Truck | 6122761227 |
ToyotaToyota | Carro importadoImport Car | 2079920799 |
ToyotaToyota | Caminhonete importadaImport Truck | 2361423614 |
E o elemento visual usa o seguinte mapeamento de exibição de dados: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"
}
}
]
}
}
}
}
]
}
No exemplo, Manufacturer
é columns
e Type
é rows
.In the sample, Manufacturer
is columns
and Type
is rows
. Há uma série criada por valores de agrupamentos por rows
(Type
).There's series created by groupings values by rows
(Type
).
E o elemento visual deve ser capaz de dividir dados por Manufacturer
e Type
também.And visual should able to slice data by Manufacturer
and Type
too.
Por exemplo, quando o usuário seleciona Chrysler
por Manufacturer
, outros elementos visuais devem mostrar os seguintes dados:For example, when user selects Chrysler
by Manufacturer
, other visuals should show following data:
FabricanteManufacturer | TipoType | ValorValue |
---|---|---|
ChryslerChrysler | Carro nacionalDomestic Car | 2888328883 |
ChryslerChrysler | Caminhonete nacionalDomestic Truck | 117131117131 |
ChryslerChrysler | Carro importadoImport Car | 00 |
ChryslerChrysler | Caminhonete importadaImport Truck | 63626362 |
Quando o usuário seleciona Import Car
por Type
(seleciona dados por série), outros elementos visuais devem mostrar os seguintes dados:When user selects Import Car
by Type
(selects data by series), other visuals should show following data:
FabricanteManufacturer | TipoType | ValorValue |
---|---|---|
ChryslerChrysler | Carro importadoImport Car | 00 |
FordFord | Carro importadoImport Car | 00 |
GMGM | Carro importadoImport Car | 197197 |
HondaHonda | Carro importadoImport Car | 29322932 |
NissanNissan | Carro importadoImport Car | 54855485 |
ToyotaToyota | Carro importadoImport Car | 2079920799 |
É necessário preencher as cestas de dados de visuais.Need to fill the visual data baskets.
Há Manufacturer
como categoria (colunas), Type
como série (linhas) e Value
como Values
para a série.There are Manufacturer
as category (columns), Type
as series (rows) and Value
as Values
for series.
Observação
Os Values
são necessários para séries porque, de acordo com o mapeamento da exibição de dados, o visual espera que Values
sejam agrupados pelos dados das Rows
.The Values
are required for series because according to data view mapping the visual expects that Values
will be grouped by Rows
data.
Criar seleções para categoriasCreate 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);
}
No código de exemplo, você pode ver que iteramos todas as categorias.In the sample code, you can see that we iterate all categories. Em cada iteração, chamamos createSelectionIdBuilder
para criar a próxima seleção para cada categoria chamando o método withCategory
do construtor de seleção.And in each iteration, we call createSelectionIdBuilder
to create the next selection for each category by calling withCategory
method of the selection builder. O método createSelectionId
é usado como um método final para retornar o objeto selection
gerado.The method createSelectionId
is used as a final method to return the generated selection
object.
No método withCategory
, passamos a coluna de category
, no exemplo, é Manufacturer
e o índice do elemento da categoria.In withCategory
method, we pass the column of category
, in the sample, it's Manufacturer
and index of category element.
Criar seleções para sériesCreate 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);
});
Criar seleções para o mapeamento da exibição de dados da tabelaCreate selections for table data view mapping
Exemplo de mapeamento de exibição de dados de tabelaSample of table data views mapping
{
"dataRoles": [
{
"displayName": "Values",
"name": "values",
"kind": "GroupingOrMeasure"
}
],
"dataViewMappings": [
{
"table": {
"rows": {
"for": {
"in": "values"
}
}
}
}
]
}
Para criar uma seleção para cada linha do mapeamento da visualização de dados da tabela, é necessário chamar o método withTable
do construtor da seleção.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();
}
}
O código do visual itera as linhas da tabela e cada linha chama o método de tabela withTable
.The visual code iterates the rows of the table and each row calls withTable
table method. Os parâmetros do método withTable
são objeto e índice table
da linha da tabela.Parameters of withTable
method are table
object and index of the table row.
Criar seleções para o mapeamento da exibição de dados da matrizCreate 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);
});
}
}
}
Na amostra, nodeWalker
chama recursivamente para cada nó e nós filhos.In the sample, nodeWalker
calls recursively for each node and child nodes.
O nodeWalker
cria o objeto nodeSelection
em cada chamada.nodeWalker
creates nodeSelection
object on each call. E cada nodeSelection
representa a selection
de nós correspondentes.And each nodeSelection
represent selection
of correspond nodes.
Selecionar pontos de dados para segmentar outros visuaisSelect datapoints to slice other visuals
Nos códigos de exemplo de seleções para o mapeamento da exibição de dados categóricos, você viu que criamos um manipulador de cliques para elementos de botão.In the sample, codes of selections for categorical data view mapping, you saw that we created a click handler for button elements. O manipulador chama o método select
do gerenciador de seleção e passa o objeto de seleção.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);
});
A interface do método select
éThe interface of select
method is
interface ISelectionManager {
// ...
select(selectionId: ISelectionId | ISelectionId[], multiSelect?: boolean): IPromise<ISelectionId[]>;
// ...
}
Você pode ver que select
pode aceitar uma variedade de seleções.You can see select
can accept an array of selections. Isso significa que seu visual pode selecionar vários pontos de dados.It means your visual can select several datapoints. O segundo parâmetro multiSelect
é responsável pela seleção múltipla.The second parameter multiSelect
responsible for multi-select. Se o valor for verdadeiro, o Power BI não limpará o estado de seleção anterior e aplicará a seleção atual; caso contrário, a seleção anterior será redefinida.If the value is true, Power BI doesn't clear the previous selection state and apply current selection otherwise previous selection will reset.
Cenário típico de uso de multiSelect
no estado do botão CTRL no evento Clicar.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);
});