[Angular] Use :host-context and the ::ng-deep selector to apply context-based styling
2024-08-31 14:19:10
If you want to style host component. You can use ':host-context'.
// host @Component({
selector: 'my-app',
template: `
<div class="styled-component">
<hostcontext-styling></hostcontext-styling>
</div>
`,
})
In the host component, we have 'styled-component' class, we want to apply some css to it from the child component:
import { Component } from '@angular/core'; @Component({
selector: 'hostcontext-styling',
template: `
<div>
I'm a div that wants to be styled
</div>
`,
styles: [
`
/* apply a border if any of our ancestors has .styled-component applied */
:host-context(.styled-component) {
border: 1px solid gray;
display:block;
}
`
]
})
export class HostContextStylingComponent {
}
Now if we want to style its child component, we can use '::ng-deep':
import { Component } from '@angular/core'; @Component({
selector: 'hostcontext-styling',
template: `
<div>
I'm a div that wants to be styled
</div>
<child-component></child-component>
`,
styles: [
`
/* apply a border if any of our ancestors has .styled-component applied */
:host-context(.styled-component) {
border: 1px solid gray;
display:block;
} :host ::ng-deep p {
background-color: yellow;
}
`
]
})
export class HostContextStylingComponent {
}
最新文章
- java高新技术-操作javaBean
- php memcache扩展 出现错误dyld: Symbol not found: _mmc_queue_free
- codeforces 689 E. Mike and Geometry Problem 组合数学 优先队列
- PHP换行符详解 PHP_EOL,<;br />;
- Part 13 Cast and Convert functions in SQL Server
- 【转】Bash中的shopt选项
- MySQL【第一篇】安装
- openerp 报表字段 report_rml_content_data
- MQ日常维护操作手册
- 算法模板——KMP字符串匹配
- Win10隐藏硬盘分区
- ThinkPhp框架:分页查询和补充框架知识
- python基础知识巩固(os.walk)
- vsftpd详细配置
- python列表1
- 剑指offer——python【第56题】删除链表中的重复节点
- PostgreSQL 使用小点
- Ajax之跨域访问与JSONP
- django2.0 官方中文文档地址
- webApi2 上传大文件代码