【问题标题】:Specifying style class for nested angular 2 component为嵌套的 Angular 2 组件指定样式类
【发布时间】:2018-06-17 01:28:35
【问题描述】:

在 my.component.html 里面说

<nested-component [class]="nestedClass"></nested-component>

然后当我想使用我的组件时,我想指定它们的样式类:

<my-component class="my-component-style" nestedClass="nested-component-style"></my-component>

上述方法不起作用(即嵌套组件未分配样式类 .nested-component-style)。您将如何修复上面的代码?欢迎使用其他解决方法。

【问题讨论】:

  • 您能详细说明一下吗?是嵌套嵌入我的组件还是相反?你的问题不清楚。
  • 它的&lt;my-component&gt;&lt;nested-component&gt;&lt;/nested-component&gt;&lt;/my-component&gt;
  • @user1589188 我不明白&lt;my-component&gt;&lt;nested-component&gt;&lt;/nested-component&gt;&lt;/my-comp‌​onent&gt; 代码。您是否直接使用此代码? .这不是声明父子的角度方式
  • @user1589188 在你的 css 文件中,将 /deep/ 放在你的类定义前面,如下所示: /deep/ .nested-component-style 看看它是否有帮助,因为这可能是样式的问题未应用于子组件。
  • @dexter 成功了!魔法!

标签: css angular


【解决方案1】:

使用

/deep/ .nested-component-style 

>>> .nested-component-style 

在父组件中将其应用于其子组件。

或者为了更安全,将您的 .nested-component-style 放在应用级别的 styles.css 中,以便对其进行全局定义。

注意浏览器不支持 /deep/ 和 >>> 选择器。

更多信息here

【讨论】:

    【解决方案2】:

    这是正确的。只需在您的子组件中添加一个@Input 变量即可链接

      @Input() nestedClass = '';
    

    【讨论】:

    • @user1589188 我只是将您的代码粘贴到我的项目中,然后在我的子组件 html 中看到类似 &lt;h1 class="nested-component-style"&gt;Hello&lt;/h1&gt; 的类
    • 是的,它会看到样式类名称,但由于某种原因,样式类附加了一个选择器,例如“my-component-style[_ngcontent-c5]”和“nested-component-style [_ngcontent-c5]”。但是是用“_ngcontent-c8”生成的,注意最后一位不同,这导致样式类无法应用于嵌套组件。
    【解决方案3】:

    my.component.html

    <nested-component class="nestedClass"></nested-component>
    

    在里面 我的.component.ts

    @Input() nestedClass: string;
    

    在 nexted.component.html 中

    <my-component class="my-component-style" [nestedClass]="'nested-component-style'"></my-component>
    

    【讨论】:

    • 是的,这就是我所拥有的,它可以看到样式类名称,但由于某种原因,样式类附加了一个选择器,例如“my-component-style[_ngcontent-c5]”和“嵌套组件样式[_ngcontent-c5]”。但是是用“_ngcontent-c8”生成的,注意最后一位不同,这导致样式类无法应用于嵌套组件。
    • 你能再看看吗?我不认为那是你所拥有的。你有 [class] 而我的是 class[nestedClass] 。这些很重要。
    • 是的,两个都试过了,都一样。但是上面的@dexter 给出了一个可行的解决方案!
    • 好酷。您可以尝试的另一个解决方案是使用 safeHTML 管道将所有内容附加为 HTML,您可以看看@答案 stackoverflow.com/questions/34585453/…>
    猜你喜欢
    • 2018-09-14
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 2017-05-26
    • 2016-11-11
    • 2017-08-04
    • 1970-01-01
    • 2019-11-08
    相关资源
    最近更新 更多