【问题标题】:matDialog doesn't open as dialogmatDialog 不作为对话框打开
【发布时间】:2018-07-06 23:54:06
【问题描述】:

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

我搜索了类似的问题,找到了这个angular2 MdDialog is not appearing as a popup但也不起作用。

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

    <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>

样式.scss

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

打开对话框

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

对话框组件

    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); }
      }
    })
  }



}

【问题讨论】:

  • 想分享您的其余组件吗?尝试在 this.dialog.open(..., {width: '250px'}) 的大括号内指定对话框的宽度
  • 用新代码更新了我的帖子。即使是一个只有 Angular Material 对话框的全新应用程序也会给出这样的结果,所以我只是遗漏了一些东西。但即使是 udemy 课程也帮不了我。
  • 您的弹出组件无关紧要,您声明它的是您的 app.module.ts 以及调用它的组件
  • 你的意思是 entryComponents 数组?
  • app.module.ts 整体,以及调用函数打开对话框/弹窗的组件或服务

标签: css angular modal-dialog angular-material2


【解决方案1】:

@Jay Cummins 的回答对我有用。 (投了赞成票,但我无法回复以添加此额外信息)

我发现将样式表放入 angular.json 并不会触发自动构建。

我在玩,试图弄清楚为什么样式可以解决问题,我发现我可以添加这个

@import '~@angular/material/prebuilt-themes/indigo-pink.css';

到我的styles.css 的顶部。这会触发重建并解决问题。

【讨论】:

  • 这对我有用。谢谢。
【解决方案2】:

我在 Angular 6 应用程序中遇到了同样的问题。解决方案是为 angular.json 文件样式属性中的样式添加预构建主题。

    "styles": [
      "src/styles.scss",
      {
        "input": "node_modules/@angular/material/prebuilt-themes/purple-green.css"
      }
    ]

【讨论】:

  • 这确实有效!但我们确实需要找出核心问题。
  • 这对我有帮助,我不知道为什么,但现在你需要自己导入样式。以前不是这样的:\
【解决方案3】:

添加style.css:

@import "~@angular/material/prebuilt-themes/indigo-pink.css";

【讨论】:

  • 为什么这被否决了?这为我解决了这个问题。
【解决方案4】:

我在 Angular 8 中遇到了同样的问题。我停止了 ng serve 并重新启动它。它重新加载并开始正常工作

【讨论】:

  • 这是我的问题,我必须在添加角度材料后重新启动应用程序
【解决方案5】:
  1. 确保您使用 MatDialog 服务打开一个对话框,而不是使用其选择器 r-create-consultant-modal 呈现它


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

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

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

@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, {

    });
  }

}

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

<button class="btn btn-primary" type="button" (click)="openDialog()">open</button>
  1. 适当地声明你的对话框,你需要将它添加到声明和入口组件中


@NgModule({
  declarations: [
    CreateConsultantModalComponent,
    DebugEnvComponent,
  ],
  imports: [
    ...
  ],
  entryComponents: [CreateConsultantModalComponent],
  providers: []
})
  1. 小步骤看看是否可以启动常规弹出窗口,然后将模板更改为 templateUrl 以重定向到 html 文件。


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(){}

}

【讨论】:

  • 材质按钮的语法是&lt;button mat-button&gt;
  • @Edric 有什么不同?这是关于对话框没有制作有角度的材质按钮。
  • 我差点要使用 ng-bootstrap 的对话服务,但是导入 bootstrap css 搞乱了整个应用的样式。由于某种原因没有导入css。 angular-cli.json 说“样式”:[“../node_modules/font-awesome/css/font-awesome.css”,“../node_modules/bootstrap/dist/css/bootstrap.min.css”,“样式.scss"],
  • 就我而言,上述步骤还不够。直到我将providers: [{provide: MAT_DIALOG_DEFAULT_OPTIONS, useValue: { }}] 添加到我的模块定义中,对话框才出现(屏幕变暗并恢复正常)
【解决方案6】:

我遇到了同样的问题,我通过再次添加角度材料解决了这个问题,因为我一开始跳过添加主题。 停止应用程序并运行,

ng add @angular/material

选择一个主题并对之后提出的所有问题回答“是”。

【讨论】:

    【解决方案7】:

    我遇到了同样的问题,hammerjs 是我的原因。我刚刚添加了使用 npm ihammerjs --save(或 npm ihammerjs@2.0.8 --save)并解决了问题。 在我的情况下,警告这个问题正在弹出 - Angular - 'Could not find HammerJS'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多