How can I pass a service variable into an Angular Material dialog?

前端 未结 5 1620
眼角桃花
眼角桃花 2020-12-24 10:40

For mdDialog, how do I pass in variable? Specifically, how to inject an Angular service into the dialog component?

5条回答
  •  鱼传尺愫
    2020-12-24 11:26

    Here's how I did it.

    pizza.service.ts

    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class PizzaService {
        getTopping(): string {
            return "Mushrooms"
        }
    }
    

    pizzaDialog.component.ts

    import { Component } from '@angular/core';
    import { MdDialogRef} from '@angular/material';
    import {PizzaService} from './pizza.service';
    
    @Component({
        selector: 'pizza-dialog',
        template: `{{pizzaTopping}}
        
        
      `,
        providers: [PizzaService]
    })
    export class PizzaDialog {
        pizzaTopping: string;
    
        constructor(public dialogRef: MdDialogRef, private pizzaService: PizzaService) { };
    
        ngOnInit(): void {
            this.pizzaTopping = this.pizzaService.getTopping()
        }
    }
    

提交回复
热议问题