简体   繁体   English

为什么我的角度材料设计选择选项不能被选中?

[英]Why can't my angular material design select options be selected?

I have just managed to populate a select dropdown menu in Angular 8 with items from Firestore.我刚刚设法用 Firestore 中的项目填充了 Angular 8 中的选择下拉菜单。 But I can't select the options, ie they show up in the dropdown, but aren't entered into the form when I click them.但我无法选择选项,即它们显示在下拉列表中,但在我单击它们时不会输入到表单中。 (The validator error message is still shown.) No errors when debugging or in browser console. (仍然显示验证器错误消息。)调试或浏览器控制台中没有错误。

UPDATE: If I remove the material design parts of the html and make it a "regular" select dropdown, like below, it works.更新:如果我删除 html 的材料设计部分并使其成为“常规”选择下拉列表,如下所示,它可以工作。 What do I need to change in the code with mat-select for it to work there too?我需要在带有mat-select的代码中更改什么才能在那里工作?

<select formControlName="moduleID" (change)="changeModule($event.target.value)">
   <option *ngFor="let module of modules" [ngValue]="module.payload.doc.data().moduleID">{{module.payload.doc.data().moduleID}}</option>
</select>

test.component.html (with the select in question in the second div): test.component.html(在第二个div中有问题的选择):

<form class="create-form" [formGroup]="stopSessionForm" novalidate (ngSubmit)="onSubmit(stopSessionForm.value)">

    <div class="form-group">
        <mat-radio-group formControlName="phase" (change)="getModules($event)">
            <mat-radio-button value=1>Phase 1</mat-radio-button>
            <mat-radio-button value=2>Phase 2</mat-radio-button>
        </mat-radio-group>
        <ng-container *ngFor="let validation of validation_messages.phase">
            <mat-error
                *ngIf="stopSessionForm.get('phase').hasError(validation.type) && (stopSessionForm.get('phase').dirty || stopSessionForm.get('phase').touched)">
                {{validation.message}}</mat-error>
        </ng-container>
    </div>

    <div class="form-group">
        <mat-form-field>
            <mat-label>Choose module/entity ID number</mat-label>
            <mat-select formControlName="moduleID" (change)="changeModule($event.target.value)">
                <mat-option *ngFor="let module of modules" [ngValue]="module.payload.doc.data().moduleID">
                    {{module.payload.doc.data().moduleID}}
                </mat-option>
            </mat-select>
            <ng-container *ngFor="let validation of validation_messages.moduleID">
                <mat-error
                    *ngIf="stopSessionForm.get('moduleID').hasError(validation.type) && (stopSessionForm.get('moduleID').dirty || stopSessionForm.get('moduleID').touched)">
                    {{validation.message}}</mat-error>
            </ng-container>
        </mat-form-field>
    </div>

    <div class="row submit-button-container">
        <button mat-raised-button class="submit-button" type="submit" [disabled]="!stopSessionForm.valid">Stop
            session</button>
    </div>
</form>

test.component.ts: test.component.ts:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { MatDialog } from '@angular/material';
import { Router } from '@angular/router';
import { FirebaseService } from '../shared/firebase.service';

@Component({
  selector: 'app-stop-session',
  templateUrl: './stop-session.component.html',
  styleUrls: ['../shared/forms.component.css']
})
export class StopSessionComponent implements OnInit {
  stopSessionForm: FormGroup;
  modules;

  validation_messages = {
    'phase': [
      { type: 'required', message: 'Phase is required.' },
    ],
    'moduleID': [
      { type: 'required', message: 'Module/entity ID number is required.' },
    ],
  };

  constructor(
    private fb: FormBuilder,
    private router: Router,
    public firebaseService: FirebaseService
  ) { }

  ngOnInit() {
    this.createForm();
    this.getModules();
  }

  getModules = () => {
    this.firebaseService
    .getModules(this.stopSessionForm.value.phase)
    .subscribe(res =>(this.modules = res));
  }

   // Choose module using select dropdown ----- NEEDED??------
   changeModule(e) {
    this.stopSessionForm.value.moduleID.setValue(e.target.value, {
      onlySelf: true
    })
    console.log(this.stopSessionForm.value.moduleID)
  }

  createForm() {
    this.stopSessionForm = this.fb.group({
      phase: ['1', Validators.required],
      moduleID: [null, Validators.required],
    });
  }

  resetFields() {
    this.stopSessionForm = this.fb.group({
      phase: new FormControl('1', Validators.required),
      moduleID: new FormControl(null, Validators.required),
    });
  }

  onSubmit(value) {
    this.firebaseService.stopSession(value)
      .then(
        res => {
          this.resetFields();
          this.router.navigate(['/stop-session']);
          window.alert('Session end data has been sent successfully!');
        })
      .catch(function (error) {
        console.error("Error writing to database: ", error);
        window.alert("Error writing to database!");
      });
  }
}

firebase.service.ts: firebase.service.ts:

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { AngularFireAuth } from "@angular/fire/auth";

@Injectable({
  providedIn: 'root'
})

export class FirebaseService {

  constructor(public afs: AngularFirestore) {}

  getModules(phase) {
    var collection:string = "ModulesPhase"+phase;
    return this.afs.collection(collection).snapshotChanges();
  }

//...

  };
}

It turns out if I change [ngValue] into [value] it works!事实证明,如果我将[ngValue]更改为[value]它会起作用!

There wasn't a problem using [ngValue] if I didn't use mat-select though (standard select instead), so I don't understand why this is so.如果我不使用mat-select (而是使用标准select ),则使用[ngValue]没有问题,所以我不明白为什么会这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我不能 select 在此 Angular Material 应用程序中添加单选按钮? - Why can't I select a radio button in this Angular Material app? 我无法以角度对齐材料设计卡 - i can't align material design cards in angular 单击所选选项的特定区域时,如何防止打开 material-ui Select 选项 - How can I prevent material-ui Select options to be opened when clicking on particular area of the selected option 如何将Angular 5 Material Select下拉菜单(mat-select)更改为打字稿代码/文件中的选项之一? - How can I change an Angular 5 Material Select dropdown (mat-select) to one of the options in typescript code/file? 使用Angular Material ToolTip但无法在其下方的元素上选择文本 - Using Angular Material ToolTip but can't select text on element beneath it Angular中的材质设计不起作用 - Material Design in Angular won't work 为什么选择标记不填充我的ng-options? - Why isn't the select tag populating my ng-options? 为什么 Firefox 不会使我禁用的 select 选项变灰? - Why won't Firefox grey out my disabled select options? 选择时禁用 Select 材料 ui 中的选项 - disable options from Select material ui when selected 为什么我在 select 菜单中看不到任何类别选项? - why i can't see any options of categories in select menu?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM