我有一个父组件:
<parent></parent>
我想使用子组件来填充这个组:
<parent>
<child></child>
<child></child>
<child></child>
</parent>
父模板:
<div class="parent">
<!-- Children goes here -->
<ng-content></ng-content>
</div>
子模板:
<div class="child">Test</div>
因为parent
和child
是两个独立的组件,所以它们的样式被锁定在自己的作用域中。
在我的父组件中,我尝试过这样做:
.parent .child {
// Styles for child
}
但是.child
样式并没有应用于child
组件。
我尝试使用styleUrls
将parent
的样式表包含到child
组件中,以解决范围问题:
// child.component.ts
styleUrls: [
'./parent.component.css',
'./child.component.css',
]
但这没有帮助,我还尝试了另一种方法,将child
样式表提取到parent
中,但这也没有帮助。
那么,如何设置包含在父组件中的子组件的样式呢?
发布于 2017-04-14 03:59:33
遗憾的是,/deep/选择器似乎已被弃用(至少在Chrome中是如此) https://www.chromestatus.com/features/6750456638341120
简而言之,(目前)除了以某种方式使子组件动态设置样式之外,似乎没有其他长期解决方案。
您可以将样式对象传递给您的孩子,并通过以下方式应用它:
<div [attr.style]="styleobject">
或者,如果你有一个特定的风格,你可以使用类似这样的东西:
<div [style.background-color]="colorvar">
发布于 2016-10-15 20:03:44
有同样的问题,所以如果你使用angular2-cli和scss/sass使用'/deep/‘而不是’>‘,最后一个选择器还不受支持(但在css中工作得很好)。
发布于 2017-04-17 11:42:18
如果您希望更多地针对实际的子组件,则应该执行以下操作。这样,如果其他子组件共享相同的类名,它们就不会受到影响。
Plunker:https://plnkr.co/edit/ooBRp3ROk6fbWPuToytO?p=preview
例如:
import {Component, NgModule } from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<div>
<h2>I'm the host parent</h2>
<child-component class="target1"></child-component><br/>
<child-component class="target2"></child-component><br/>
<child-component class="target3"></child-component><br/>
<child-component class="target4"></child-component><br/>
<child-component></child-component><br/>
</div>
`,
styles: [`
/deep/ child-component.target1 .child-box {
color: red !important;
border: 10px solid red !important;
}
/deep/ child-component.target2 .child-box {
color: purple !important;
border: 10px solid purple !important;
}
/deep/ child-component.target3 .child-box {
color: orange !important;
border: 10px solid orange !important;
}
/* this won't work because the target component is spelled incorrectly */
/deep/ xxxxchild-component.target4 .child-box {
color: orange !important;
border: 10px solid orange !important;
}
/* this will affect any component that has a class name called .child-box */
/deep/ .child-box {
color: blue !important;
border: 10px solid blue !important;
}
`]
})
export class App {
}
@Component({
selector: 'child-component',
template: `
<div class="child-box">
Child: This is some text in a box
</div>
`,
styles: [`
.child-box {
color: green;
border: 1px solid green;
}
`]
})
export class ChildComponent {
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, ChildComponent ],
bootstrap: [ App ]
})
export class AppModule {}
希望这能有所帮助!
codematrix
https://stackoverflow.com/questions/36527605
复制相似问题