Why styles in not applied to dynamically create container?

Viewed 34

I have a component with reference. I pass this reference to service where after promise I create a new container in host component:

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.scss'],
  providers: [MapService],
})
export class MapComponent implements OnInit {
   constructor(private el: ElementRef, private mapService: MapService) {
       this.mapService.set(this.el.nativeElement);
   } 
}

As result I get this DOM structure:

<app-map>
    <div id="created"></div>
</app-map>

Why when I try to style map.component.scss it does not applied to this container:

#created {
    padding: 10px;
    background: #ccc;
    width: 400px;
    height: 300px;
}

Result DOM element looks:

<app-map time="3000" _nghost-rpv-c11="" ng-version="11.0.9">
   <div id="created"></div>
</app-map>
2 Answers

it is expected. that is how angular style encapsulation works. to fix it remove the encapsulation for this component by

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.scss'],
  providers: [MapService],
  encapsulation: ViewEncapsulation.None // here we turn of styles modification for this component
})

you can couple of options here

  1. declare the created style globally i.e. use "styles.scss" and add the style there, that will be applied irrespective of component boundary.

  2. use ng deep in the component scss i.e. in map.component.scss use

    :host::ng-deep {
       #created {
           padding: 10px;
           background: #ccc;
           width: 400px;
           height: 300px;
       }
     }
    

3rd ofcourse is to remove style isolation, but that is dangerous as any style declared in map.component.scss will be applicable globally without component boundary.

Related