微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular 9 升级仅在启用 Ivy 时导致 matPrefix 和 mat-form-field 的样式问题

如何解决Angular 9 升级仅在启用 Ivy 时导致 matPrefix 和 mat-form-field 的样式问题

在将我的项目从 Angular 8 更新到 9 之后,一些 Angular 材质 mat-form-field 控件最终出现了奇怪的样式问题。

在将生成代码与旧的 Angular 8 版本进行比较时,我注意到在材质输入控件中添加了一些新的 css 类(例如:ng-tns-c157-20)。其中有很多,我发现了一个类似的问题 here 。有一种解决方法可以清除那些新引入的样式类。但这在这种情况下无济于事。

这仅在启用 Ivy 时发生,如果我从编译器选项中禁用 Ivy,则不会发生并且一切正常。

问题之一是输入表单字段内的图标前缀与标签/占位符重叠。

enter image description here

当在编译器选项中禁用 Ivy 时,它会发生如下变化,就像在 Angular 8 中一样。

enter image description here

看起来有一个类似的错误 bug raised in 2018 并且仍然打开。但是,我的问题仅在启用 Ivy 时发生。

这是我生成输入控件的模板的一部分。

<ng-container *ngIf="formField; else standalone">
    <mat-form-field [appearance]="formField.appearance" [color]="formField.color" [floatLabel]="formField.floatLabel"
        [formGroup]="formField.formGroup" [hiderequiredMarker]="formField.hiderequiredMarker" [hintLabel]="formField.hintLabel">
        <mat-label *ngIf="formField.label">{{formField.label}}</mat-label>
        <ng-template *ngIf="formField.prefix" matPrefix hspElement [context]="context"
            [element]="formField.prefix" (command)="onCommand($event)"></ng-template>
        <input matInput
            [attr.id]="getValue('id')" [ngClass]="getValue('cssClass')" [style.display]="getValue('hidden')?'none':undefined"
            [attr.fieldName]="getValue('placeholder')||undefined" [attr.placeholder]="getValue('placeholder')||undefined"
            [formControlName]="controlName" [required]="required"
            [attr.maxLength]="getValue('maxLength')||undefined" [attr.minLength]="getValue('minLength')||undefined"
            [attr.readonly]="getValue('readOnly')||undefined" [type]="type" (keypress)="onKeyPress($event)" />
        <ng-template *ngIf="formField.suffix" matSuffix hspElement [context]="context"
            [element]="formField.suffix" (command)="onCommand($event)"></ng-template>
        <ng-container *ngFor="let validator of validators" ngProjectAs="mat-error">
            <mat-error *ngIf="hasError(validator)">{{getError(validator)}}</mat-error>
        </ng-container>
    </mat-form-field>
</ng-container>

按如下方式禁用 Ivy 可以解决问题:

angularCompilerOptions": {
    ....
    "enableIvy": false
  }

我更感兴趣的是为什么 Ivy 会改变样式。根据 Angular 9 更新说明,这是一项幕后改进。

有人遇到过这种情况吗?有谁知道除了禁用 Ivy 或使用 !important 添加样式之外是否还有其他解决方法

解决方法

style.scss

中使用这些样式
.mat-form-field-appearance-fill:not(.mat-focused) .mat-form-field-label {
  margin-top: 0;
}

.mat-form-field-appearance-outline:not(.mat-focused) .mat-form-field-label {
  margin-top: 0.25em;
}

或者,如果您希望它用于单个组件,请将其放入 component.scss 并将组件的 encapsulation 设置为 ViewEncapsulation.None

错误:https://stackblitz.com/edit/angular-xfexy1

使用 style.scss 修复:https://stackblitz.com/edit/angular-xfexy1-joi5v4

使用 component.scss 修复:https://stackblitz.com/edit/angular-xfexy1-khj6mi

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。