gpt4 book ai didi

更改 nativeElement.className 后 css 类不生效

转载 作者:行者123 更新时间:2023-12-04 10:28:33 27 4
gpt4 key购买 nike

所以我正在编写一个 Angular 应用程序,并且我正在尝试重新设计一个 mat-form-field。

HTML:

<mat-form-field  #matFormField class="example-full-width" >
<input #autocompleteInput type="text" placeholder="Enter {{searchBy.value}}" aria-label="Number" matInput [formControl]="myControl"
[matAutocomplete]="auto" (keyup.enter)="onEnter()">
<fa-icon [icon]="faSearch"></fa-icon>
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let option of autocompleteList" [value]="option" (onSelectionChange)="autocompleteSelected($event)">
{{option[searchBy.value]}}
</mat-option>
</mat-autocomplete>
</mat-form-field>

typescript :

@ViewChild('matFormField', { static: false, read: ElementRef}) formField: ElementRef;

ngAfterViewInit(): void {
this.formField.nativeElement.children[0].children[0].children[0].className = 'mat-form-field-infix-fix';
}

SCSS:

mat-form-field {
width: 100%;
}

.mat-form-field-infix-fix {
display: flex;
position: relative;
flex: auto;
min-width: 0;
}

fa-icon {
float: right;
}

我可以看到肯定应用了类名:

screen capture of web developer tools inspecting div showing div.mat-form-field-infix-fix

但由于某些原因,CSS 不是:

missing css in developer tools

有人知道这里发生了什么吗?

最佳答案

我相信您遇到了讨论的 View Encapsulation here .值得注意的点:

As discussed earlier, component CSS styles are encapsulated into the component's view and don't affect the rest of the application.

以及之前在样式范围部分的讨论:

The styles specified in @Component metadata apply only within the template of that component.

They are not inherited by any components nested within the template nor by any content projected into the component.

因此,要让您的 css 影响嵌套组件样式,您有几个选择:

  1. 更改 View 封装设置
  2. 将此样式放入应用程序的全局样式表中
  3. 在组件的 css 中,使用特殊的 piercing rules例如 ::ng-deep(很有用,但 Angular 团队已经弃用了这些,但没有提供好的替代方案)

关于更改 nativeElement.className 后 css 类不生效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60527532/

27 4 0