프로그래밍/Angular

[Angular] 프로젝션, 쉐도우 돔 (Shadow DOM)의 역할

Jay Tech 2017. 12. 30. 04:57
반응형

Angular는 부모 컴포넌트의 템플릿 일부를 자식 컴포넌트 템플릿에 넣을 수 있다.


import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { NgModule, Component, ViewEncapsulation } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

@Component({
selector : 'child',
styles : ['.wrapper { background : lightgreen; }'],
template : `
<div class="wrapper">
<h2>Child</h2>
<div>This div is defined in the child's template</div>
<ng-content></ng-content>
</div>
`,
encapsulation : ViewEncapsulation.Native
})
class ChildComponent {}

@Component({
selector : 'app',
styles : ['.wrapper { background : cyan; }'],
template : `
<div class="wrapper">
<h2>Parent</h2>
<div>This div is defined in the Parent's template</div>
<child>
<div>Parent projects this div onto the child </div>
</child>
</div>
`,
encapsulation : ViewEncapsulation.Native
})
class AppComponent {}

@NgModule({
imports : [BrowserModule],
declarations : [AppComponent, ChildComponent],
bootstrap : [AppComponent]
})
class AppModule {}

platformBrowserDynamic().bootstrapModule(AppModule);


자식 컴포넌트 템플릿에 <ng-content> 태그를 넣으면 부모 컴포넌트에서 보내는 템플릿의 위치가 결정 된다.


 encapsulation : ViewEncapsulation.Native


이것은 Shadow DOM 에 관한 내용이다. Shadow DOM은 웹 컴포넌트 표준 중 하나이다. 모든 웹 페이지는 DOM 객체의 계층으로 구성되지만 Shadow DOM 은 전역 DOM과 분리된 별개의 DOM 계층을 구성한다. 이 Shadow DOM은 HTML 문서내에 포함되어 렌더링 되지만, HTML 문서에 해당하는 전역 DOM에서 Shadow DOM 내부의 엘리먼트에 접근할 수 없다.


ViewEncapsulation의 옵션을 Emulated로 줄 때 : Angular가 제공하는 방식으로 DOM을 캡슐화한다. 


Native일 때는 브라우저가 지원하는 Shadow DOM을 사용한다.



이 예제를 실행 했을 때 개발자 도구를 확인해 보면,


wrapper 클래스에 적용되는 스타일이 부모 따로 자식 따로 적용이 되는 것을 알 수 있다.

#shadow-root는 부모 컴포넌트와 분리된 DOM을 생성하기 때문에 부모 컴포넌트의 스타일은 자식에 적용이 되지 않는다.


출처 : Angular Development with Typescript - 한장현


반응형