matDialog不会以对话框的形式打开

时间:2018-01-27 23:45:15

标签: css angular modal-dialog angular-material2

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

我搜索了类似的问题,发现这个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>

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



}

7 个答案:

答案 0 :(得分:2)

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

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

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

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

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

答案 1 :(得分:1)

我在Angular 6应用中遇到了同样的问题。解决方案是在seen文件样式属性中为样式添加一个预先构建的主题。

angular.json

enter image description here

答案 2 :(得分:1)

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

ng add @angular/material

选择一个主题,然后回答所有问题。

答案 3 :(得分:0)

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

  2. 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. 适当地声明您的对话框,您需要将其添加到声明和条目组件

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

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

答案 4 :(得分:0)

我在Angular 8中遇到了同样的问题。我停止了f = a[:, 0] f - f[:, None] ,然后重新启动了它。重新加载并开始正常工作

答案 5 :(得分:0)

我遇到了同样的问题,hammerjs是我的原因。我刚刚添加了 npm i Hammerjs --save(或npm i Hammerjs@2.0.8 --save),它解决了这个问题 。 就我而言,在警告中此问题正在弹出-Angular - 'Could not find HammerJS'

答案 6 :(得分:-1)

添加style.css

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