【问题标题】:Angular 6 - Styles are not working when using ng-contentAngular 6 - 使用 ng-content 时样式不起作用
【发布时间】:2018-11-04 01:15:57
【问题描述】:

我有一些代码,但我在使用 <ng-content></ng-content> 时遇到了未定位的 css 问题

代码如下:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-embed',
  template: `<ng-content></ng-content>`,
  styles: [`

  app-embed {
    position:relative;
     width:100%;
     height:0;
     padding-bottom:33%;
  }

 app-embed iframe {
    width: 100vw;
    height: 56.25vw;
  }`]
})
export class AppEmbedComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

我该如何解决这个问题?

【问题讨论】:

    标签: angular typescript angular6


    【解决方案1】:

    您应该将内容的样式放在嵌入它们的组件中。如果您想设置AppEmbedComponent 标签的样式,那么您需要使用:host 伪选择器来执行此操作。

    embed.component.ts

    @Component({
      selector: 'app-embed',
      template: `<ng-content></ng-content>`,
      styles: [`
        :host {
          position:relative;
          width:100%;
          height:0;
          padding-bottom:33%;
        }
      `],
    })
    export class AppEmbedComponent {}
    

    other.component.ts

    @Component({
      selector: 'app-other',
      template: `
        <app-embed>
          <iframe src="//www.google.com"></iframe>
        </app-embed>
      `,
      styles: [`
        iframe {
          width: 100vw;
          height: 56.25vw;
        }
      `],
    })
    export class AppOtherComponent {}
    

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-06
      • 1970-01-01
      • 1970-01-01
      • 2020-08-31
      • 2019-03-01
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多