我正在遵循使用 Material 选择字段的示例:https://material.angular.io/components/select/overview
我的 ts 文件中有这个列表:
accessTypes: string[] = [
'New Employee', 'Rehire', 'New Provider', 'New Resident/Fellow', 'Transfer/Job Title Change',
'New Contractor/Vendor', 'New Student/Intern', 'Change to existing user'
];
我可以制作一个简单的下拉列表并轻松获取值:
<select class="md-col-6 numberEight" [(ngModel)]="model.accessType">
<option *ngFor="let item of accessTypes" [value]="item">{{item}}</option>
</select>
但是当我尝试使用 mat-select 时,示例中的 css 未应用,并且列表选项一直显示在屏幕底部:
<div class="question">
<div class="row">
<h5>8. Type of Access Request</h5><p class="required">*</p>
</div>
<div class="col-md-6">
<mat-form-field appearance="fill">
<mat-label>Access Types</mat-label>
<mat-select [(ngModel)]="model.accessType">
<mat-option *ngFor="let item of accessTypes" [value]="item">
{{item}}
</mat-option>
</mat-select>
</mat-form-field>
</div>
</div>
这就是它的样子:
然后列表选项一直出现在页面底部:
我的 css 文件中根本没有任何样式会影响选择字段中的任何内容。 question
类没有样式,而 required
只是将 * 设为红色。
即使我在一个全新的组件中执行此操作,其中的 html 文件仅包含:
<mat-form-field appearance="fill">
<mat-label>Access Types</mat-label>
<mat-select [(ngModel)]="this.accessTypes" placeholder="Choose...">
<mat-option *ngFor="let item of accessTypes" [value]="item">
{{item}}
</mat-option>
</mat-select>
</mat-form-field>
其行为相同。
那么为什么会发生这种情况呢?为什么列表不像示例中那样显示?该示例是否排除了一些必要的样式?
我发现了这个类似的问题:Mat Select appears in the bottom of the page并尝试将 @import "~@angular/material/prebuilt-themes/indigo-pink.css";
添加到页面 css 文件中,但这并没有解决问题。
我有
import {MatSelectModule} from '@angular/material/select';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
我还包含在 package.json 中:
"@ng-bootstrap/ng-bootstrap": "^9.1.0",
"bootstrap": "^4.5.0",
在 angular.json 中,我将其包含在样式中:
"styles": [
"node_modules/bootstrap/dist/css/bootstrap.css",
"src/styles.css"
],
在脚本中:
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.js"
]
在我的应用程序模块中。我还需要什么吗/这些有错吗?我已经拥有的 Bootstrap 是否会以某种方式影响选择列表的样式?
我无法共享整个 html 页面,因为它使问题太长,但如果您需要其他任何内容,请告诉我。
最佳答案
您的代码似乎在我的测试元素中正常工作,并且您的导入看起来正确。您可能有一些东西覆盖了 Material 选择样式,或者您的 Angular Material 结构中缺少一些东西。使用 class="col-md-6"
告诉我您正在使用某种样式引导框架?
更新:
我启动了一个仅指定 .css 的新元素,看起来我能够重现该问题。看来您确实缺少 Material 主题结构。我将 @import "~@angular/material/prebuilt-themes/indigo-pink.css";
添加到 styles.css
文件中,它解决了问题。
styles.css 文件:
/* You can add global styles to this file, and also import other style files */
@import "~@angular/material/prebuilt-themes/indigo-pink.css";
html, body { height: 100%; }
body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }
关于css - Angular Material 选择样式行为不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73378615/