I have an Angular application using Angular Material, and I want to open a div
element in a dialog when I click a button. Additionally, I need to ensure that the data flow within the div
remains uninterrupted.
Here’s what I have so far:
- In my
app
component, I have adiv
that logs a timer using RxJS. This is to ensure the data flow continues even when the dialog is open. - I used
@ViewChild
to capture the element and pass it to the dialog.
However, my approach doesn’t seem to work. I want the div
to move into the dialog when the button is clicked and return to the original template when the dialog is closed, all without breaking the data flow.
Here’s my example code:
import '@angular/localize/init';
import {
Component,
ViewChild,
importProvidersFrom,
inject,
} from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient } from '@angular/common/http';
import { provideAnimations } from '@angular/platform-browser/animations';
import { VERSION as CDK_VERSION } from '@angular/cdk';
import {
VERSION as MAT_VERSION,
MatNativeDateModule,
} from '@angular/material/core';
import { timer } from 'rxjs';
import { CommonModule } from '@angular/common';
import { Dialog } from '@angular/cdk/dialog';
/* eslint-disable no-console */
console.info('Angular CDK version', CDK_VERSION.full);
console.info('Angular Material version', MAT_VERSION.full);
@Component({
selector: 'app-root',
imports: [CommonModule],
template: `
in app
<div #foo>{{now | async | json}}</div>
<button (click)="openDialog()">open dialog</button>
`,
standalone: true,
})
export class AppComponent {
@ViewChild('foo') foo: any;
dialog = inject(Dialog);
now = timer(0, 5 * 1000);
openDialog() {
const dialogRef = this.dialog.open(this.foo);
}
}
bootstrapApplication(AppComponent, {
providers: [
provideAnimations(),
provideHttpClient(),
importProvidersFrom(MatNativeDateModule),
],
}).catch((err) => console.error(err));
Stackblitz demo
What is the correct way to achieve this behavior in Angular with Material?