Angular Integration
Supports: Angular 12+ • TypeScript 4.0+ • Stencil v2.9.0+
Stencil can generate Angular component wrappers for your web components. This allows your Stencil components to be used within an Angular application. The benefits of using Stencil's component wrappers over the standard web components include:
- Angular component wrappers will be detached from change detection, preventing unnecessary repaints of your web component.
- Web component events will be converted to RxJS observables to align with Angular's
@Output()and will not emit across component boundaries.
- Optionally, form control web components can be used as control value accessors with Angular's reactive forms or
[ngModel].
- It is not necessary to include the
Angular
CUSTOM_ELEMENTS_SCHEMAin all modules consuming your Stencil components.
 
 
We recommend using a monorepo structure for your component library with component wrappers. Your project workspace should contain your Stencil component library and the library for the generated Angular component wrappers.
An example project set-up may look similar to:
top-most-directory/
├── stencil-library/
│   ├── stencil.config.js
│   └── src/components
└── angular-workspace/
    └── projects/
        └── component-library/
            └── src/
                ├── lib/
                └── public-api.ts
 If you already have an Angular component library, skip this section.
The first time you want to create the component wrappers, you will need to have an Angular library package to write to.
Using Angular's CLI, generate a workspace and a library for your Angular component wrappers:
npx -p @angular/cli ng new angular-workspace --no-create-application
cd angular-workspace
npx -p @angular/cli ng generate library component-library
 If you already have a Stencil component library, skip this section.
npm init stencil components stencil-library
cd stencil-library
# Install dependencies
npm install
# or if using yarn
yarn install 
 Install the
@stencil/angular-output-target dependency to your Stencil component library package.
# Install dependency
npm install @stencil/angular-output-target --save-dev
# or if using yarn
yarn add @stencil/angular-output-target --devIn your project's stencil.config.ts, add the angularOutputTarget configuration to the
outputTargets array:
import { angularOutputTarget } from '@stencil/angular-output-target';
export const config: Config = {
  namespace: 'stencil-library',
  outputTargets: [
    // By default, the generated proxy components will
    // leverage the output from the `dist` target, so we
    // need to explicitly define that output alongside the
    // Angular target
    {
      type: 'dist',
    },
    angularOutputTarget({
      componentCorePackage: 'your-stencil-library-package-name',
      directivesProxyFile: '../angular-workspace/projects/component-library/src/lib/stencil-generated/components.ts',
      directivesArrayFile: '../angular-workspace/projects/component-library/src/lib/stencil-generated/index.ts',
    }),
  ],
};The
directivesProxyFileis the relative path to the file that will be generated with all of the Angular component wrappers. You will replace the file path to match your project's structure and respective names. You can generate any file name instead ofcomponents.ts.
The
directivesArrayFileis the relative path to the file that will be generated with a constant of all the Angular component wrappers. This constant can be used to easily declare and export all the wrappers.
See the API section below for details on each of the output target's options.
You can now build your Stencil component library to generate the component wrappers.
# Build the library and wrappers
npm run build
# or if using yarn
yarn run buildIf the build is successful, you will now have contents in the file specified in
directivesProxyFile and
directivesArrayFile.
You can now finally import and export the generated component wrappers for your component library. For example, in your library's main Angular module:
import { DIRECTIVES } from './stencil-generated';
@NgModule({
  declarations: [...DIRECTIVES],
  exports: [...DIRECTIVES],
})
export class ExampleLibraryModule {}Any components that are included in the exports array should additionally be exported in your main entry point (either
public-api.ts or
index.ts). Skipping this step will lead to Angular Ivy errors when building for production.
export { DIRECTIVES } from './stencil-generated';NOTE: The default behavior does not automatically define the Web Components needed by the proxy components. You can manually define the Web Components following the documentation for the dist output target.
 If you are using a monorepo tool (Lerna, Nx, etc.), skip this section.
Before you can successfully build a local version of your Angular component library, you will need to link the Stencil package to the Angular package.
From your Stencil project's directory, run the following command:
# Link the working directory
npm link
# or if using yarn
yarn linkFrom your Angular component library's directory, run the following command:
# Link the package name
npm link name-of-your-stencil-package
# or if using yarn
yarn link name-of-your-stencil-packageThe name of your Stencil package should match the
name property from the Stencil component library's
package.json.
Your component libraries are now linked together. You can make changes in the Stencil component library and run
npm run build to propagate the
changes to the Angular component library.
NOTE: As an alternative to
npm link, you can also runnpm installwith a relative path to your Stencil component library. This strategy, however, will modify yourpackage.jsonso it is important to make sure you do not commit those changes.
 
 This section covers how developers consuming your Angular component wrappers will use your package and component wrappers.
If you distributed your components through a primary NgModule, developers can simply import that module into their implementation to use your components.
import { ExampleLibraryModule } from 'your-angular-library-package-name';
@NgModule({
  imports: [ExampleLibraryModule],
})
export class FeatureModule {}Alternatively, developers can individually import the components and declare them on a module:
import { MyComponent } from 'your-angular-library-package-name';
@NgModule({
  declarations: [MyComponent],
  exports: [MyComponent],
})
export class FeatureModule {}Developers can now directly leverage your components in their template and take advantage of Angular template binding syntax.
<my-component first="Your" last="Name"></my-component> 
 
 Required
Type: string
The title of the Stencil package where components are available for consumers (i.e. the
name property value in your Stencil project's
package.json).
This is used during compilation to write the correct imports for components.
For a starter Stencil project generated by running:
npm init stencil component my-component-libThe componentCorePackage would be set to:
// stencil.config.ts
export const config: Config = {
  ...,
  outputTargets: [
    angularOutputTarget({
      componentCorePackage: 'my-component-lib',
      // ... additional config options
    })
  ]
}Which would result in an import path like:
import { MyComponent } from 'my-component-lib/components/my-component.js'; 
 Optional
Default: 'dist/components'
If
includeImportCustomElements is
true, this option can be used to specify the directory where the generated
custom elements live. This value only needs to be set if the
dir field on the dist-custom-elements output target was set to something other than
the default directory.
 
 Optional
Default: []
Type: string[]
This lets you specify component tag names for which you don't want to generate Angular wrapper components. This is useful if you need to write framework-specific versions of components. For instance, in Ionic Framework, this is used for routing components - like tabs - so that Ionic Framework can integrate better with Angular's Router.
 
 Optional
Default: null
Type: string
Used to provide a list of type Proxies to the Angular Component Library. See Ionic Framework for a sample.
 
 Required
Type: string
This parameter allows you to name the file that contains all the component wrapper definitions produced during the compilation process. This is the first file you should import in your Angular project.
 
 Optional
Default: false
Type: boolean
If true, Angular components will import and define elements from the
dist-custom-elements build, rather than
dist. For more information
on using the
dist-custom-elements output for the Angular proxies, see the
FAQ answer below.
 
 Optional
Default: []
Type: ValueAccessorConfig[]
This lets you define which components should be integrated with
ngModel (i.e. form components). It lets you set what the target prop is (i.e.
value),
which event will cause the target prop to change, and more.
const angularValueAccessorBindings: ValueAccessorConfig[] = [
  {
    elementSelectors: ['my-input[type=text]'],
    event: 'myChange',
    targetAttr: 'value',
    type: 'text',
  },
];
export const config: Config = {
  namespace: 'stencil-library',
  outputTargets: [
    angularOutputTarget({
      componentCorePackage: 'component-library',
      directivesProxyFile: '{path to your proxy file}',
      valueAccessorConfigs: angularValueAccessorBindings,
    }),
    {
      type: 'dist',
      esmLoaderPath: '../loader',
    },
  ],
}; 
 dist output target?
 
 No! By default, this output target will look to use the
dist output, but the output from
dist-custom-elements can be used alternatively.
To do so, simply set the includeImportCustomElements option in the output target's config and ensure the
custom elements output target is added to the Stencil config's output target array:
// stencil.config.ts
export const config: Config = {
  ...,
  outputTargets: [
    // Needs to be included
    {
      type: 'dist-custom-elements'
    },
    angularOutputTarget({
      componentCorePackage: 'component-library',
      directivesProxyFile: '{path to your proxy file}',
      // This is what tells the target to use the custom elements output
      includeImportCustomElements: true
    })
  ]
}Now, all generated imports will point to the default directory for the custom elements output. If you specified a different directory
using the
dir property for dist-custom-elements, you need to also specify that directory for the Angular output target. See
the API section for more information.
In addition, all the Web Component will be automatically defined as the generated component modules are bootstrapped.
 
Event names shouldn’t include special characters when initially written in Stencil, try to lean on using camelCased event names for interoperability between frameworks.
You can configure how your input events can map directly to a value accessor, allowing two-way data-binding to be a built in feature of any of your components. Take a look at valueAccessorConfig's option below.
 
 If you want your custom elements to be able to work on older browsers, you should add the
applyPolyfills() that surround the
defineCustomElements() function.
import { applyPolyfills, defineCustomElements } from 'test-components/loader';
...
applyPolyfills().then(() => {
  defineCustomElements();
}); 
Once included, components could be referenced in your code using
ViewChild and
ViewChildren as in the following example:
import { Component, ElementRef, ViewChild } from '@angular/core';
import { TestComponent } from 'test-components';
@Component({
  selector: 'app-home',
  template: `<test-components #test></test-components>`,
  styleUrls: ['./home.component.scss'],
})
export class HomeComponent {
  @ViewChild(TestComponent) myTestComponent: ElementRef<TestComponent>;
  async onAction() {
    await this.myTestComponent.nativeElement.testComponentMethod();
  }
}
 Usually when beginning this process, you may bump into a situation where you find that some of the interfaces you've used in your Stencil component
library aren't working in your Angular component library. You can resolve this issue by adding an
interfaces.d.ts file located within the root
of your Stencil component library's project folder, then manually exporting types from that file e.g.
export * from './components';
When adding this file, it's also recommended to update your package.json's types property to be the distributed file, something like:
"types": "dist/types/interfaces.d.ts"
Contributors
Contents
- Setup 
- Project Structure 
- Creating an Angular Component Library 
- Creating a Stencil Component Library 
- Adding Angular Output Target 
- Link your packages (optional) 
- Consumer Usage 
- API 
- componentCorePackage 
- customElementsDir 
- excludeComponents 
- directivesArrayFile 
- directivesProxyFile 
- includeImportCustomElements 
- valueAccessorConfigs 
- FAQs 
- Do I have to use the dist output target? 
- What is the best format to write event names? 
- How do I bind input events directly to a value accessor? 
- How do I add IE11 or Edge support? 
- How do I access components with ViewChild or ViewChildren? 
- Why aren't my custom interfaces exported from within the index.d.ts file? 
Thanks for your interest!
We just need some basic information so we can send the guide your way.


















