[Angular 2] Controlling how Styles are Shared with View Encapsulation

Style and View Encapsulation is best understood by seeing how each option (Emulated, Native, and None) compare to each other.

 

复制代码
<html>
<head>
    <title>Angular 2 QuickStart</title>
    <style>
        .started{
            background-color: #0b97c4;
        }
        .completed{
            background-color: #80d8ff;
        }
    </style>
    <script src="../node_modules/systemjs/dist/system.src.js"></script>
    <script src="../node_modules/angular2/bundles/angular2.dev.js"></script>
    <script>
        System.config({
            packages: {'app': {defaultExtension: 'js'}}
        });
        System.import('app/app');
    </script>
</head>
<div class="started">Started</div>
<div class="completed">Completed</div>
<body>
<app>Loading...</app>
</body>
</html>
复制代码

 

复制代码
import {Input, Component, View, NgClass, ViewEncapsulation} from "angular2/angular2";
import {TodoModel} from './todoService';

@Component({
    selector: 'todo-item-render'
})
@View({
    encapsulation: ViewEncapsulation.Emulated, // default state: the global style will have an affect on compoment style
    directives: [NgClass],
    styles: [`
        .${TodoModel.STARTED}{
            color: green;
        }

        .${TodoModel.COMPLETED}{
            text-decoration: line-through;
        }
    `],
    template: `
       <div>
           <span [ng-class]="todoinput.status">{{todoinput.title}}</span>
           <button (click)="todoinput.toggle()">Toggle</button>
       </div>
    `
})

export class TodoItemRender{
    @Input() todoinput: TodoModel;
}
复制代码

 

if we switch to Native:

encapsulation: ViewEncapsulation.Native, // Use shadow down, which mean the global style will not affect the compoment sytle

last, we switch to None:

encapsulation: ViewEncapsulation.None, // the component style and global style are the same, affect each other

posted @   Zhentiw  阅读(437)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2013-10-28 Dynamic Programming for TSP
点击右上角即可分享
微信分享提示