Non-Angular 앱에서 Angular 구성 요소 사용

우리 모두는 대부분 구성 요소 기반 접근 방식을 알고 있으며 해당 기술 환경 내에서 작동하는 특정 기술로 구성 요소를 만듭니다. Like angular 컴포넌트는 angular에서만 동작하고 Vue로 만든 Component는 Vue에서만 동작합니다.

But what if I want to use a component I have created with angular on other platforms?



웹 구성요소란 무엇인가부터 시작한 다음 Angular를 사용하여 이 마법을 수행해 봅시다.

웹 컴포넌트



Web components are a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use in web pages and web apps. Custom components and widgets build on the Web Component standards, will work across modern browsers, and can be used with any JavaScript library or framework that works with HTML.



<script type="module" src="./js/my-element.js"></script>
...
<my-element></my-element>

사용자 정의 요소를 사용하는 것은 위의 코드와 같이 매우 간단하며 this article에서 javascript에서 생성하는 방법도 찾을 수 있습니다.

이 문서는 Angular를 사용하여 이러한 웹 구성 요소를 만드는 방법에 관한 것이므로 나중에 단일 파일을 가져오기만 하면 해당 요소를 어디에서나 사용할 수 있으므로 하나 만들어 보겠습니다.

  • 1단계 각도 프로젝트 만들기

    ng new web-components



  • 2단계 요소 라이브러리 추가

    ng add @angular/elements



  • Step-3 생성된 디렉토리 내에 웹 컴포넌트 생성

    ng generate component my-element



  • 4단계 구성 요소에 코드 작성

    I will create a simple counter component having two buttons for increment and decrement of the counter.


  • 5단계 app.module.ts 파일을 열고 다음을 수행합니다.
    다음 가져오기

  • import { Injector } from '@angular/core';
    import {createCustomElement} from '@angular/elements';
    

    AppComponent 선언을 제거하고 부트스트랩에서도 제거합니다.
    app.component.ts 및 관련 HTML, CSS 및 spec.ts 파일을 제거하고 가져오기
  • @NgModule({}) 안에 구성 요소를 시작 구성 요소로 추가합니다.

  • entryComponents: [MyElementComponent]
    

  • AppModule 클래스에 Injector를 삽입하고 사용자 정의 요소를 정의합니다.

  • export class AppModule { 
      constructor(private injector: Injector) {}
      ngDoBootstrap() {
        const el = createCustomElement(MyElementComponent, { injector: this.injector });
        customElements.define('my-element', el);
      }
    

  • 6단계 구성 요소에 코드를 작성합니다...

  • 7단계 프로젝트 빌드

    ng build --prod --output-hashing none



  • 8단계 dist에서 생성된 파일 번들
    main.js, pollyfill.js runtime.js 및 scripts.js를 포함하여 여러 파일이 dist 폴더에 생성됩니다. 최신 버전에서는 두 가지 유형의 파일이 생성됩니다(es2015 및 es5 포함).
    파일을 단일 파일로 연결하려면
    먼저 연결에 필요한 종속성을 설치합니다.

    npm install fs-extra concat



  • 기본 폴더에 js 파일을 만들고 다음 코드를 포함합니다. 이름을 bundle.js로 지정합니다.

    const fs = require('fs-extra');
    const concat = require('concat');
    (async function build() {
        const files = [
            './dist/web-components/runtime-es5.js',
            './dist/web-components/polyfills-es5.js',
            './dist/web-components/scripts-es5.js',
            './dist/web-components/main-es5.js',
        ]
        await fs.ensureDir('elements')
        await concat(files, 'elements/my-element.js');
        await fs.copyFile('./dist/web-components/styles.css', 'elements/styles.css')    
    })()
    

  • 9단계 다음 코드를 실행하여 모든 파일을 연결합니다.
    > 노드 번들.js

  • elements라는 이름의 새 폴더가 생성되며 이제 생성된 파일을 가져오고 app.module.ts에서 사용자 정의 요소를 만들 때 언급한 요소를 렌더링하여 해당 요소를 사용할 수 있습니다.

    <script src="my-element.js" ></script>
    <h4>Element below is created in angular</h4>
    <my-element></my-element>
    

  • 10단계 이제 브라우저에서 해당 HTML 파일을 실행하면 이제 angular에서 생성된 구성 요소가 간단한 HTML 페이지에서 작동하는 것을 볼 수 있습니다.
    다음은 코드펜 데모입니다.


  • 다음은 각도 코드입니다.


    마울리크데스 / 웹 구성 요소


    이 프로젝트는 각진 웹 요소를 만들기 위한 샘플입니다.

    좋은 웹페이지 즐겨찾기