내용으로 건너뛰기
Angular 7.0의 슬롯이 있는 Angular 요소의 콘텐츠 프로젝션

Angular 7.0의 슬롯이 있는 Angular 요소의 콘텐츠 프로젝션

Angular 7에서 슬롯이 있는 Angular 요소의 콘텐츠 프로젝션에 대해 알아보세요.

3min read

이 기사에서는 Angular 요소에 콘텐츠를 투영하는 방법을 배웁니다. 현재로서는 다음 목록에 표시된 대로 ng-content를 사용하여 콘텐츠 프로젝션을 수행한다는 것을 알고 있습니다.

import { Component } from '@angular/core';
@Component({
    selector: 'app-greet',
    template: `
 <h2>{{title}}</h2>
 <ng-content></ng-content>
`
})
export class GreetComponent {
    title = 'Greet';
}

다음 목록에 표시된 대로 콘텐츠를 투영할 수도 있습니다.

<h1>Welcome to {{ title }}!</h1>
<app-greet>
      <h3>Hello Foo</h3>
</app-greet>

위의 접근 방식의 문제는 "GreetComponent를 Angular 요소로 사용하면 콘텐츠를 투영할 수 없다는 것입니다. 이를 더 잘 이해하기 위해 GreetComponent를 Angular 요소로 변환하는 것부터 시작하겠습니다.  여기에서 배우는 것이 좋습니다 단계적으로 Angular 요소를 만듭니다.

GreetComponent를 Angular Element로 변환한 후 AppModule은 아래 목록과 같아야 합니다.

import { AppComponent } from './app.component';
import { GreetComponent } from './greet.component';
 
@NgModule({
    declarations: [
        AppComponent, GreetComponent
    ],
    imports: [
        BrowserModule
    ],
    providers: [],
    bootstrap: [GreetComponent],
    entryComponents: [GreetComponent]
})
export class AppModule {
 
    constructor(private injector: Injector) {
        const customElement = createCustomElement(GreetComponent, { injector });
        customElements.define('app-root', customElement);
    }
 
    ngDoBootstrap() {
 
    }
}

이제 아래 목록과 같이 index.html에서 GreetComponent를 사용할 수 있습니다.

<body>
     <!-- <app-root></app-root> -->
     <app-greet>
         <h2>hey Foo</h2>
     </app-greet>
</body>

응용 프로그램을 실행하면 <h2> 요소가 Angular 요소 GreetComponent에 프로젝션되지 않았음을 알 수 있습니다.

애플리케이션을 실행하면 <h2>요소가 Angular 요소 GreetComponent에 프로젝션되지 않았습니다.

Angular 7부터는 콘텐츠 프로젝션 슬롯을 수행할 수 있는 다른 옵션이 있습니다. Angular Element에서 콘텐츠 프로젝션을 수행하려면 다음을 수행해야 합니다.

  1. Set ViewEnacpsulation to ShadowDom
  2. <ng-content 대신 슬롯 사용 >

아래 목록과 같이 GreetComponent를 수정해 보겠습니다.

import { Component, ViewEncapsulation } from '@angular/core';
@Component({
    selector: 'app-greet',
    template: `
 <h2>{{title}}</h2>
 <slot name='message'></slot>
`,
    encapsulation: ViewEncapsulation.ShadowDom
})
export class GreetComponent {
    title = 'Greet Component';
}

캡슐화를 ShadowDom으로 설정하고 <ng-content>를 <slot로 대체했습니다>

Angular 처음부터 Shadow Dom을 지원해 왔습니다. Angular 6.0까지는 세 가지 캡슐화 모드가 있었습니다

  1. Emulated
  2. 토종의
  3. 없음

에뮬레이션은 기본 모드였으며 네이티브 모드는 섀도우 돔 V.0을 만드는 데 사용되었습니다. Angular 6.1부터 Angular Shadow Dom V.1을 지원하기 시작했습니다. 네 번째 옵션 ShadowDom을 사용하여 구성 요소에서 Shadow Dom V.1을 활성화할 수 있습니다. 캡슐화를 ShadowDom으로 설정하면 Angular Shadow Dom V.1이 생성됩니다. Angular Element에서 콘텐츠 프로젝션을 수행하려면 캡슐화를 ShadowDom으로 설정해야 합니다.

이제 응용 프로그램을 실행하면 아래 이미지와 같이 콘텐츠가 투영되었음을 알 수 있습니다.

애플리케이션을 실행하면 이미지에 표시된 대로 콘텐츠가 투영되었음을 알 수 있습니다

따라서 ShadowDom 캡슐화 모드와 슬롯을 사용하면 Angular 7.0의 Angular 요소에 콘텐츠를 투영할 수 있습니다.  이 게시물이 도움이 되었기를 바랍니다. 읽어 주셔서 감사합니다.  이 게시물이 마음에 드시면 공유해 주세요. 또한 Infragistics Ignite UI for Angular 구성 요소를 확인하지 않았다면 반드시 확인해 보세요! 그들은 50+ Material 기반 Angular 구성 요소를 사용하여 웹 앱을 더 빠르게 코딩할 수 있도록 도와줍니다.

데모 요청