Replies: 2 comments
|
Yep, totally doable — subscribe to the autocomplete's <input matInput [matAutocomplete]="auto" (matAutocompleteSelected)="open($event.option.value)">
open(value: any) { this.dialog.open(MyDialog, { data: { value } }); }Inside the dialog, inject |
|
Quick heads up: bind the event to Here is a clean, modern Angular implementation using standalone components, 1. TemplateBind <mat-form-field appearance="outline">
<mat-label>Select an option</mat-label>
<input type="text" matInput [formControl]="searchControl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="openSelectionDialog($event)">
<mat-option *ngFor="let option of options" [value]="option">
{{ option }}
</mat-option>
</mat-autocomplete>
</mat-form-field>(If you are on Angular 17+, you can replace 2. Component TSHandle import { Component, inject } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';
import { SelectionDialogComponent, SelectionDialogData } from './selection-dialog.component';
@Component({
selector: 'app-item-selector',
templateUrl: './item-selector.component.html'
})
export class ItemSelectorComponent {
private readonly dialog = inject(MatDialog);
searchControl = new FormControl('');
options: string[] = ['Alpha', 'Beta', 'Gamma', 'Delta'];
openSelectionDialog(event: MatAutocompleteSelectedEvent) {
const selectedValue = event.option.value;
this.dialog.open<SelectionDialogComponent, SelectionDialogData>(
SelectionDialogComponent,
{
data: { item: selectedValue },
width: '380px'
}
);
}
}3. Dialog ComponentRead the value cleanly via import { Component, inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
import { MatButtonModule } from '@angular/material/button';
export interface SelectionDialogData {
item: string;
}
@Component({
selector: 'app-selection-dialog',
standalone: true,
imports: [MatDialogModule, MatButtonModule],
template: `
<h2 mat-dialog-title>Selected Option</h2>
<mat-dialog-content>
<p>You selected: <strong>{{ data.item }}</strong></p>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-flat-button color="primary" mat-dialog-close>OK</button>
</mat-dialog-actions>
`
})
export class SelectionDialogComponent {
readonly data = inject<SelectionDialogData>(MAT_DIALOG_DATA);
}This ensures full type-safety between the caller and the dialog, avoids template parsing issues, and works seamlessly across current Angular versions. |
Uh oh!
There was an error while loading. Please reload this page.
Hey there!
I'm learning how to use Material Angular and I was wondering if there is a way to open a dialog after selecting a option in the autocomplete component. I need the value selected to be shown into the dialog.
Thank you so much!
All reactions