matDialog 不作为对话框打开

它不是作为停留弹出窗口打开,而是作为页面底部左对齐的块打开.

我搜索了类似的问题,发现这个angular2 MdDialog is not appearing作为弹出窗口但也不起作用.

做了一个干净的页面,也许是我的其他一些 css 干扰了,但不是.

 <div><h4 mat-dialog-title>新顾问</h4></div><mat-dialog-content><div *ngIf="!allFieldsAreFilledIn()" class="alert alert-info"><strong>{{ getAddFeedback('emptyFields') }}</strong></div><div ngbDropdown class="d-inline-block"><button class="btn btn-outline-primary" id="dropdownBasic1" ngbDropdownToggle>{{ currentNewConsultant.user ?currentNewConsultant.user.lastName + " " + currentNewConsultant.user.firstName : activeUsers[0].lastName+ " " + activeUsers[0].firstName }}</button><div ngbDropdownMenu aria-labelledby="dropdownBasic1"><button class="dropdown-item" *ngFor="let user of activeUsers" (click)="updateNewConsultantProperty(user, 'user')">{{user.lastName + " " + user.firstName}}</按钮></div></div><div ngbDropdown class="d-inline-block"><button class="btn btn-outline-primary" id="dropdownBasic1" ngbDropdownToggle>{{ currentNewConsultant.unitManager != null ?currentNewConsultant.unitManager.lastName + " " + currentNewConsultant.unitManager.firstName: unitManagers[0].lastName + " " + unitManagers[0].firstName }}</button><div ngbDropdownMenu aria-labelledby="dropdownBasic1"><button class="dropdown-item" *ngFor="let um of unitManagers" (click)="updateNewConsultantProperty(um, 'unitManager')">{{um.lastName + " " + um.firstName}}</按钮></div></div><div ngbDropdown class="d-inline-block"><button class="btn btn-outline-primary" id="dropdownBasic1" ngbDropdownToggle>{{ currentNewConsultant.profile ?currentNewConsultant.profile.name : userRoles[0].name}}</button><div ngbDropdownMenu aria-labelledby="dropdownBasic1"><button class="dropdown-item" *ngFor="let profile of userRoles" (click)="updateNewConsultantProperty(profile, 'profile')">{{profile.name}}</button></div></div><!-- 选择内部 --><div 类="crudElement"><label class="crudLabel" style="padding-top: 7px;">Internal?:</label><div class="btn-group crudEditElement" 下拉菜单><button type="button" class="btn green-button dropdown-margin-min-width" dropdownToggle>{{ currentNewConsultant.internal ?'内部外部' }}<span class="caret"></span></按钮><ul *dropdownMenu role="menu" aria-labelledby="single-button" class="dropdownItems dropdown-menu dropdown-margin-min-width"><li role="menuitem" (click)="updateNewConsultantProperty('Internal', 'internal')"><a class="dropdown-item">内部</a></li><li role="menuitem" (click)="updateNewConsultantProperty('External', 'internal')"><a class="dropdown-item">外部</a></li></ul></div></div><div class="form-group"><label for="hometown">家乡:</label><input type="text" class="form-control" name="hometown" [(ngModel)]="currentNewConsultant.hometown" 需要></div><div class="form-group"><label for="skills">技能:</label><input type="text" class="form-control" name="skills" [(ngModel)]="currentNewConsultant.skills" 需要></div><div class="form-group"><label for="comment">评论:</label><textarea class="form-control" name="comment" [(ngModel)]="currentNewConsultant.comment" required></textarea></div><div class="form-group"><label for="individualCost">个人成本:</label>您确定要添加新顾问 {{ currentNewConsultant.user.lastName + ' ' + currentNewConsultant.user.firstName}}?</div>

样式.scss

@import '~@angular/material/prebuilt-themes/purple-green.css';

打开对话框

private openDialog(): void {让 dialogRef = this.dialog.open(CreateConsultantModalComponent, {});}

对话框组件

 从'@angular/core'导入{组件,OnInit,输出};从'../../../service/consultant.service'导入{ConsultantService};从'../../../service/unit.service'导入{ UnitService };从'../../../service/profile.service'导入{ ProfileService};从'../../../service/user.service'导入{用户服务};从'app/model/consultant.model'导入{顾问};从'../../../model/unit.model'导入{单位};从'app/model/profile.model'导入{配置文件};从'app/model/user.model'导入{用户};@零件({选择器:'r-create-consultant-modal',templateUrl: './create-consultant-modal.component.html',styleUrls: ['./create-consultant-modal.component.scss'],提供者:[ConsultantService、UnitService、ProfileService、UserService]})导出类 CreateConsultantModalComponent 实现 OnInit {公共顾问:顾问[] = [];公共顾问FilteredList:顾问[] = [];公共 currentNewConsultant: 顾问 = null;公共单位:单位[] = [];公共单元列表:字符串[] = [];公共用户角色:个人资料[] = [];公共单元管理器:用户[] = [];公共活动用户:用户[] = [];构造函数(私人顾问服务:ConsultantService,私有单元服务:单元服务,私有profileService:ProfileService,私人用户服务:用户服务){this.getAllConsultants();this.getAllUnits();this.getAllRoles();this.getAllFreeAndActiveUsers();this.getAllUnitManagers();this.currentNewConsultant = 新顾问(空,空,空,空,空,真,0,空,空,空,真,空);this.currentNewConsultant.unitManager = null;}ngOnInit() {}私人getAddFeedback(emptyFields?:字符串):字符串{如果(!emptyFields){let message = "Can't add a Consultant without a ";if (!this.activeUsers) 消息 += '用户';返回消息 += '!';}return '所有字段都是必需的!'}私人 updateNewConsultantProperty($event: any, property: string): void {开关(属性){案例用户":this.currentNewConsultant.user = $事件;休息;案例内部":this.currentNewConsultant.internal = $event == '内部';休息;案例'unitManager':this.currentNewConsultant.unitManager = $事件;休息;案例简介":this.currentNewConsultant.profile = $事件;休息;默认:console.log('没有为新顾问的 updateProperty 实现');}}公共取消(){}私有 allFieldsAreFilledIn() {让 c = this.currentNewConsultant;返回 c.user&&c.内部&&c.家乡&&c.技能&&c.评论&&c. 个人成本;}公共保存(){如果(this.activeUsers){this.currentNewConsultant.profile = new Profile(this.userRoles[0].id, this.userRoles[0].name, this.userRoles[0].rate);this.currentNewConsultant.user = this.activeUsers[0];}如果(this.unitManagers){让 max = this.activeUsers.length;而(--最大){if (this.activeUsers[max].role.toUpperCase() == 'UM') {让 um = this.activeUsers[max];this.currentNewConsultant.unitManager = new User(um.id, um.unit, um.userActivityLogs, um.email, um.password,um.firstName、um.lastName、um.shortName、um.employeeNumber、um.role、um.active);}}}}私人getAllConsultants(){this.consultantService.getConsultants().subscribe(顾问列表=>{顾问列表.forEach(c => this.consultants.push(新顾问(c.id, c.user,c.profile, c.proposition,c.availableFrom,c.internal,c.individualCost,c.hometown, c.skills, c.comment, c.active, c.plannings, c.unitManager)));},错误=>{console.log("获取顾问数据失败.错误信息:" + error.message);});}私人 getAllUnits() {this.unitService.findAllUnits().subscribe(单元列表 =>{让 unitNames = ['All'];unitList.forEach(unit => unitNames.push(unit.name));this.unitList = unitNames;this.units = 单元列表;},错误=>{console.log("获取单位数据失败.错误信息:" + error.message);});}私人 getAllRoles() {this.profileService.findAllProfiles().subscribe(roles => {this.userRoles = 角色;})}私人 getAllUnitManagers() {this.userService.findAllUnitManagers().subscribe(ums => {this.unitManagers = ums;})}私人 getAllFreeAndActiveUsers() {//应该在后端完成,但时间不够 :'(, 我很抱歉this.userService.findAllActiveUsers().subscribe(users => {const amountOfConsultants = this.consultants.length;const amountOfUsers = users.length;for (让 j = 0; j 

解决方案

  1. 确保您使用 MatDialog 服务打开一个对话框,而不是使用其选择器 r-create-consultant-modal 呈现它


import {Component, OnInit} from '@angular/core';从@angular/material"导入 { MatDialog};从'./create-consultant-modal.component'导入{CreateConsultantModalComponent};

让我们说功能打开的组件(或服务)

@Component({选择器:'app-debug-env',templateUrl: './debug-env.component.html',styleUrls: ['./debug-env.component.css']})导出类 DebugEnvComponent 实现 OnInit {构造函数(公共对话框:MatDialog){}ngOnInit() { }私人开放对话():无效{让 dialogRef = this.dialog.open(CreateConsultantModalComponent, {});}}

和带有简单按钮的html调用组件功能(或服务功能)

<button class="btn btn-primary" type="button" (click)="openDialog()">open</button>

  1. 适当地声明你的对话框,你需要将它添加到声明和入口组件中


@NgModule({声明:[创建ConsultantModalComponent,调试环境组件,],进口:[...],entryComponents:[CreateConsultantModalComponent],提供者:[]})

  1. 小步骤看看是否可以启动常规弹窗,然后将模板更改为 templateUrl 以重定向到 html 文件.


import {Component, OnInit} from '@angular/core';@零件({选择器:'r-create-consultant-modal',模板:'<p>弹出</p>',提供者:[]})导出类 CreateConsultantModalComponent 实现 OnInit {构造函数(){}ngOnInit(){}}

Instead of opening as a layover popup, it opens as a block on the bottom of the page left aligned.

I searched for similar problems, found this angular2 MdDialog is not appearing as a popup but also doesn't work.

Made a clean page, maybe it was some of my other css that interfered, but nope.

    <div>
  <h4 mat-dialog-title>New consultant</h4>
</div>
<mat-dialog-content>
  <div *ngIf="!allFieldsAreFilledIn()" class="alert alert-info">
    <strong>{{ getAddFeedback('emptyFields') }}</strong>
  </div>
  <div ngbDropdown class="d-inline-block">
    <button class="btn btn-outline-primary" id="dropdownBasic1" ngbDropdownToggle>{{ currentNewConsultant.user ? currentNewConsultant.user.lastName + " " + currentNewConsultant.user.firstName : activeUsers[0].lastName
      + " " + activeUsers[0].firstName }}</button>
    <div ngbDropdownMenu aria-labelledby="dropdownBasic1">
      <button class="dropdown-item" *ngFor="let user of activeUsers" (click)="updateNewConsultantProperty(user, 'user')">{{user.lastName + " " + user.firstName}}</button>
    </div>
  </div>

  <div ngbDropdown class="d-inline-block">
    <button class="btn btn-outline-primary" id="dropdownBasic1" ngbDropdownToggle>{{ currentNewConsultant.unitManager != null ? currentNewConsultant.unitManager.lastName + " " + currentNewConsultant.unitManager.firstName
      : unitManagers[0].lastName + " " + unitManagers[0].firstName }}</button>
    <div ngbDropdownMenu aria-labelledby="dropdownBasic1">
      <button class="dropdown-item" *ngFor="let um of unitManagers" (click)="updateNewConsultantProperty(um, 'unitManager')">{{um.lastName + " " + um.firstName}}</button>
    </div>
  </div>

  <div ngbDropdown class="d-inline-block">
    <button class="btn btn-outline-primary" id="dropdownBasic1" ngbDropdownToggle> {{ currentNewConsultant.profile ? currentNewConsultant.profile.name : userRoles[0].name}}</button>
    <div ngbDropdownMenu aria-labelledby="dropdownBasic1">
      <button class="dropdown-item" *ngFor="let profile of userRoles" (click)="updateNewConsultantProperty(profile, 'profile')">{{profile.name}}</button>
    </div>
  </div>

  <!-- Selecting Internal -->
  <div class="crudElement">
    <label class="crudLabel" style="padding-top: 7px;">Internal?:</label>
    <div class="btn-group crudEditElement" dropdown>
      <button type="button" class="btn green-button dropdown-margin-min-width" dropdownToggle>
        {{ currentNewConsultant.internal ? 'Internal' : 'External' }}
        <span class="caret"></span>
      </button>
      <ul *dropdownMenu role="menu" aria-labelledby="single-button" class="dropdownItems dropdown-menu dropdown-margin-min-width">
        <li role="menuitem" (click)="updateNewConsultantProperty('Internal', 'internal')">
          <a class="dropdown-item">Internal</a>
        </li>
        <li role="menuitem" (click)="updateNewConsultantProperty('External', 'internal')">
          <a class="dropdown-item">External</a>
        </li>
      </ul>
    </div>
  </div>

  <div class="form-group">
    <label for="hometown">Hometown:</label>
    <input type="text" class="form-control" name="hometown" [(ngModel)]="currentNewConsultant.hometown" required>
  </div>

  <div class="form-group">
    <label for="skills">Skills:</label>
    <input type="text" class="form-control" name="skills" [(ngModel)]="currentNewConsultant.skills" required>
  </div>

  <div class="form-group">
    <label for="comment">Comment:</label>
    <textarea class="form-control" name="comment" [(ngModel)]="currentNewConsultant.comment" required></textarea>
  </div>
  <div class="form-group">
    <label for="individualCost">Individual Cost:</label>
    <input type="number" class="form-control" name="individualCost" step="0.5" [(ngModel)]="currentNewConsultant.individualCost"
      required>
  </div>


  <!--ADDING / SAVING-->
  <div *ngIf="activeUsers && allFieldsAreFilledIn()">
    <button [ngStyle]="{'display' : (addConfirming ? 'none' : '')}" type="button" class="btn btn-success" (click)="save()">Add
    </button>
    <div [ngStyle]="{'display' : (addConfirming ? '' : 'none')}">
      <div>
        Are you certain you want to add the new Consultant {{ currentNewConsultant.user.lastName + ' ' + currentNewConsultant.user.firstName
        }}?
      </div>
      <button style="margin-right: 5px; margin-top: 10px;" type="submit" class="btn btn-danger " (click)="cancel()">
        <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
      </button>
      <button style="margin-top: 10px;" type="button" class="btn btn-success" (click)="save()">
        <span class="glyphicon glyphicon-check" aria-hidden="true"></span>
      </button>
    </div>
  </div>
  <div *ngIf="!activeUsers" class="alert alert-danger text-center" style="margin-top: 20px;">
    <strong>{{ getAddFeedback() }}</strong>
  </div>
</mat-dialog-content>

Styles.scss

@import '~@angular/material/prebuilt-themes/purple-green.css';

Open the dialog

private openDialog(): void {
    let dialogRef = this.dialog.open(CreateConsultantModalComponent, {
    });
  }

dialog component

    import { Component, OnInit, Output } from '@angular/core';
import { ConsultantService } from '../../../service/consultant.service';
import { UnitService } from '../../../service/unit.service';
import { ProfileService } from '../../../service/profile.service';
import { UserService } from '../../../service/user.service';
import { Consultant } from 'app/model/consultant.model';
import { Unit } from '../../../model/unit.model';
import { Profile } from 'app/model/profile.model';
import { User } from 'app/model/user.model';


@Component({
  selector: 'r-create-consultant-modal',
  templateUrl: './create-consultant-modal.component.html',
  styleUrls: ['./create-consultant-modal.component.scss'],
  providers: [ConsultantService, UnitService, ProfileService, UserService]
})
export class CreateConsultantModalComponent implements OnInit {

  public consultants: Consultant[] = [];
  public consultantsFilteredList: Consultant[] = [];
  public currentNewConsultant: Consultant = null;

  public units: Unit[] = [];
  public unitList: string[] = [];
  public userRoles: Profile[] = [];
  public unitManagers: User[] = [];
  public activeUsers: User[] = [];


  constructor(private consultantService: ConsultantService,
    private unitService: UnitService,
    private profileService: ProfileService,
    private userService: UserService) {
      this.getAllConsultants();
      this.getAllUnits();
      this.getAllRoles();
      this.getAllFreeAndActiveUsers();
      this.getAllUnitManagers();
      this.currentNewConsultant = new Consultant(null, null, null, null, null, true, 0, null, null, null, true, null);
      this.currentNewConsultant.unitManager = null;
     }


    ngOnInit() {

    }

    private getAddFeedback(emptyFields?: string): string {
      if (!emptyFields) {
        let message = "Can't add a Consultant without a ";

        if (!this.activeUsers) message += 'User';

        return message += '!';
      }
      return 'All fields are required!'
    }

    private updateNewConsultantProperty($event: any, property: string): void {
      switch (property) {

        case 'user':
        this.currentNewConsultant.user = $event;
          break;
        case 'internal':
        this.currentNewConsultant.internal = $event == 'Internal';
          break;
        case 'unitManager':
        this.currentNewConsultant.unitManager = $event;
          break;
        case 'profile':
        this.currentNewConsultant.profile = $event;
          break;
        default:
          console.log('NOT IMPLEMENTED for updateProperty on NEW Consultant');
      }
    }

    public cancel(){}

    private allFieldsAreFilledIn() {
      let c = this.currentNewConsultant;
      return c.user
        && c.internal
        && c.hometown
        && c.skills
        && c.comment
        && c.individualCost;
    }


  public save() {

    if (this.activeUsers) {
        this.currentNewConsultant.profile = new Profile(this.userRoles[0].id, this.userRoles[0].name, this.userRoles[0].rate);
        this.currentNewConsultant.user = this.activeUsers[0];
    }

    if (this.unitManagers) {
      let max = this.activeUsers.length;
      while (--max) {
        if (this.activeUsers[max].role.toUpperCase() == 'UM') {
          let um = this.activeUsers[max];
          this.currentNewConsultant.unitManager = new User(um.id, um.unit, um.userActivityLogs, um.email, um.password,
             um.firstName, um.lastName, um.shortName, um.employeeNumber, um.role, um.active);
        }
      }
    }

  }
  private getAllConsultants() {
    this.consultantService.getConsultants().subscribe(
      consultantList => {
        consultantList.forEach(c => this.consultants.push(
          new Consultant(
            c.id, c.user,
            c.profile, c.proposition,
            c.availableFrom, c.internal, c.individualCost,
            c.hometown, c.skills, c.comment, c.active, c.plannings, c.unitManager)
          )
        );
      },
      error => {
        console.log("Failed to get consultants data. Error message: " + error.message);
      }
    );
  }

  private getAllUnits() {
    this.unitService.findAllUnits().subscribe(
      unitList => {
        let unitNames = ['All'];
        unitList.forEach(unit => unitNames.push(unit.name));
        this.unitList = unitNames;
        this.units = unitList;
      },
      error => {
        console.log("Failed to get units data. Error message: " + error.message);
      }
    );
  }

  private getAllRoles() {
    this.profileService.findAllProfiles().subscribe(roles => {
      this.userRoles = roles;
    })
  }

  private getAllUnitManagers() {
    this.userService.findAllUnitManagers().subscribe(ums => {
      this.unitManagers = ums;
    })
  }

  private getAllFreeAndActiveUsers() {
    // Should be done in the backend but lack of time :'(, my apologies
    this.userService.findAllActiveUsers().subscribe(users => {
      const amountOfConsultants = this.consultants.length;
      const amountOfUsers = users.length;
      for (let j = 0; j < amountOfConsultants; j++) {
        for (let i = 0; i < amountOfUsers; i++) {
          const user = users[i];
          if (user && user.email === this.consultants[j].user.email && user.role === 'Admin') {
            users[i] = null;
          }
        }
      }

      for (let k = 0; k < amountOfUsers; k++) {
        const user = users[k];
        if (user) { this.activeUsers.push(user); }
      }
    })
  }



}

解决方案

  1. Make sure you're openning a dialog box with MatDialog service, and not rendering it using its selector r-create-consultant-modal


import {Component, OnInit} from '@angular/core';

import { MatDialog} from '@angular/material';
import {CreateConsultantModalComponent} from './create-consultant-modal.component';

Lets say component (or service) with function open

@Component({
  selector: 'app-debug-env',
  templateUrl: './debug-env.component.html',
  styleUrls: ['./debug-env.component.css']
})
export class DebugEnvComponent implements OnInit {

  constructor(public dialog: MatDialog) {}

  ngOnInit() { }

  private openDialog(): void {
    let dialogRef = this.dialog.open(CreateConsultantModalComponent, {

    });
  }

}

and html with simple button to call component function (or service function)

<button class="btn btn-primary" type="button" (click)="openDialog()">open</button>

  1. Declare your dialog box appropriately, you need to add it to declaration and entrycomponents


@NgModule({
  declarations: [
    CreateConsultantModalComponent,
    DebugEnvComponent,
  ],
  imports: [
    ...
  ],
  entryComponents: [CreateConsultantModalComponent],
  providers: []
})

  1. Baby steps see if you can launch a regular pop up, then change template to templateUrl to redirect to the html file.


import {Component, OnInit} from '@angular/core';

@Component({
  selector: 'r-create-consultant-modal',
  template: '<p> Pop Up </p>',
  providers: []
})
export class CreateConsultantModalComponent implements OnInit {

  constructor(){}
  ngOnInit(){}

}

相关文章