Angular material 之 dialog 弹框实战

本文详细介绍了如何在Angular项目中使用Material设计的对话框组件,包括创建弹出按钮和页面的步骤,以及如何通过代码实现对话框的打开和关闭功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

功能虽然简单,但是我更具官网上做出来是报错的,所以自己记录一下,希望可以帮到别人

首先,创建一个组件用于存放弹出按钮

在创建一个组件,存放弹出页面

直接上代码:

根:

非常重要,需要将弹出页面加载进去,不然弹不出来哦

在存放弹出按钮的地方:

总体:

// import { Component, OnInit } from '@angular/core';
import {MediaMatcher} from '@angular/cdk/layout';
import {ChangeDetectorRef, Component} from '@angular/core';

import {MatDialog} from '@angular/material/dialog';
import {NewsComponent} from './news/news.component';

export interface DialogData {
  animal: string;
  name: string;
}

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent  {


  
  animal: string;
  name: string;

  mobileQuery: MediaQueryList;


  private _mobileQueryListener: () => void;

  constructor(changeDetectorRef: ChangeDetectorRef, media: MediaMatcher,
    public dialog: MatDialog //弹出框
    ) {
    this.mobileQuery = media.matchMedia('(max-width: 700px)');
    this._mobileQueryListener = () => changeDetectorRef.detectChanges();
    this.mobileQuery.addListener(this._mobileQueryListener);
  }


  openDialog(): void {  
   
    //弹出
    const dialogRef = this.dialog.open(NewsComponent, {
      width: '250px',
      data: {name: this.name, animal: this.animal}
    });

    dialogRef.afterClosed().subscribe(result => {
      this.animal = result;
    });
  }

 
}


页面很简单,一个button就行

要才弹出的页面ts

import { Component, OnInit,Inject} from '@angular/core';
import { DialogData } from 'src/app/components/dialog/dialog.component';
import { MatDialogRef, MAT_DIALOG_DATA} from '@angular/material/dialog';

@Component({
  selector: 'app-news',
  templateUrl: './news.component.html',
  styleUrls: ['./news.component.scss']
})
export class NewsComponent implements OnInit {

  constructor(
    public dialogRef: MatDialogRef<NewsComponent>,
    @Inject(MAT_DIALOG_DATA) public data: DialogData){
    }

  ngOnInit() {
  }


}

弹出页面自己写

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值