Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

angular - How to style ng-content

Am following this tutorial on transclusion https://scotch.io/tutorials/angular-2-transclusion-using-ng-content

However there is no mention on how to style elements that end up replacing ng-content.

It seems that I can only target those element in the css if preceeded by the /deep/ keyword, which is normally used when targeting a nested component. Is this correct?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Content inside <ng-content> is insulated from the component. It can't see the component's attributes or styling.

If you do need to style it, and sometimes you will, you have two options:

1. Just write CSS

You can create a regular CSS file and style the content like that. You are almost certainly using the shadow DOM polyfill. Regular CSS will see through the polyfill and just style the element. Say you have an app-sidebar. You could write:

app-sidebar p {
  color:red;
}

If you are using ng-cli, any rules you write in style.scss will be global.

2. Use the :host /deep/ selector

If you want to use the shadow DOM polyfill and style your components using the style or styleUrls attribute of the Component decorator, select the element with :host, then ignore the shadow DOM polyfill with the /deep/ child selector.

  • :host will select the element.
  • /deep/ will select elements without adding the mock shadow DOM attribute selector to the nested selectors.

Put them together and you can select all elements nested inside the host component element, regardless of where they are declared.

like so:

:host /deep/ p {
  color:red;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...