Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
更改nativeElement.className后css类不生效_Css_Angular Material - Fatal编程技术网

更改nativeElement.className后css类不生效

更改nativeElement.className后css类不生效,css,angular-material,Css,Angular Material,所以我在写一个angular应用程序,我试图重新设计一个mat表单字段的样式 HTML: <mat-form-field #matFormField class="example-full-width" > <input #autocompleteInput type="text" placeholder="Enter {{searchBy.value}}" aria-label="Number" matInput [formControl]="myControl"

所以我在写一个angular应用程序,我试图重新设计一个mat表单字段的样式

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>
SCSS:

我可以看出类名是明确应用的:

但出于某些原因,css不是:


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

我相信您遇到了所讨论的视图封装。值得注意的是:

如前所述,组件CSS样式被封装到组件的视图中,不会影响应用程序的其余部分

以及前面在“样式范围”部分中的讨论:

@Component metadata中指定的样式仅适用于该组件的模板

它们不会被嵌套在模板中的任何组件继承 也不受投射到组件中的任何内容的影响

因此,要使css实现嵌套组件样式,您有几个选项:

  • 更改视图封装设置
  • 将此样式放在应用程序的全局样式表中
  • 在组件的css中,使用特殊的,如
    ::ng deep
    (很有用,但Angular团队已经弃用了它们,但没有提供一个好的替代方案)
  • @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';
    }
    
    mat-form-field {
      width: 100%;
    }
    
    .mat-form-field-infix-fix {
      display: flex;
      position: relative;
      flex: auto;
      min-width: 0;
    }
    
    fa-icon {
      float: right;
    }