How do you deal with div with mat-card-header-text in an material2 card?

后端 未结 10 1528
逝去的感伤
逝去的感伤 2021-02-18 20:04

I can\'t seem to wrap my head around having this container in an md card.

In my material cards, I have this:

&
10条回答
  •  走了就别回头了
    2021-02-18 20:32

    This behavior is the result of Angular 2/4's view encapsulation, which in Emulated mode will only inject (via style elements) component styles that match elements actually in your view template.

    So if you try to override a .mat-* style like so:

    .mat-card-header-text {
      height: auto;
      margin: 0;
    }
    

    but your HTML looks like this:

    
      face
      {{user.name}}
      {{user.status | userStatus}}
    
    

    then the .mat-card-header-text rule won't be injected into the DOM, since the injector doesn't see such an element in your template.

    The simplest workaround is to directly include the div.mat-card-header-text element in your template:

    
      face
      
    {{user.name}} {{user.status | userStatus}}

    Edit: as you pointed out, this generates an extra empty div.mat-card-header-text, so it's not an ideal solution. The only way to fix that is if you create your own card component based on md-card (possibly using component inheritence), but at that point you'd just modify the component's CSS directly.

    Otherwise, you can switch the view encapsulation mode for your component to None:

    import { ViewEncapsulation } from '@angular/core';
    
    @Component({
      moduleId: module.id,
      selector: 'user-card',
      templateUrl: 'user-card.component.html',
      styleUrls: ['user-card.component.css'],
      encapsulation: ViewEncapsulation.None
    })
    ...
    

    Though if you do that, the :host selector will no longer work, so you'll need to replace it with the selector you specified in the @Component decorator:

    user-card {
       ...
    }
    

提交回复
热议问题