Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

ngx-bind-io

EndyKaufman38MIT1.0.1TypeScript support: included

Directives for auto binding Input() and Output() from host component to inner in Angular9+ application

angular, ng, ngx, input, output, directives, dynamic, auto, bind, binding, inheritance, hierarchy, nested, class, component, extends, angular, angular9

readme

Greenkeeper badge Build Status npm version

Directives for auto binding Input() and Output() from host component to inner in Angular9+ application

Example

Without auto binding inputs and outputs

<component-name (start)="onStart()" [isLoading]="isLoading$ | async" [propA]="propA" [propB]="propB"> </component-name>

With auto binding inputs and outputs

<component-name [bindIO]> </component-name>

Installation

npm i --save ngx-bind-io

Demo - Demo application with ngx-bind-io.

Stackblitz - Simply sample of usage on https://stackblitz.com

Usage

app.module.ts

import { NgxBindIOModule } from 'ngx-bind-io';
import { InnerComponent } from './inner.component';
import { HostComponent } from './host.component';

@NgModule({
  ...
  imports: [
    ...
    NgxBindIOModule.forRoot(), // in child modules import as "NgxBindIOModule"
    ...
  ]
  declarations: [
    ...
    InnerComponent,
    HostComponent
    ...
  ],
  ...
})
export class AppModule { }

inner.component.ts

import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { BindIoInner } from 'ngx-bind-io';

@BindIoInner() // <-- need for correct detect manual inputs like [propName]="propValue"
@Component({
  selector: 'inner',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div *ngIf="isLoading">Loading... (5s)</div>
    <button (click)="onStart()">Start</button> <br />
    {{ propA }} <br />
    {{ propB }}
  `
})
export class InnerComponent {
  @Input()
  isLoading: boolean = undefined;
  @Input()
  propA = 'Prop A: not defined';
  @Input()
  propB = 'Prop B: not defined';
  @Output()
  start = new EventEmitter();
  onStart() {
    this.start.next(true);
  }
}

base-host.component.ts

import { BehaviorSubject } from 'rxjs';

export class BaseHostComponent {
  isLoading$ = new BehaviorSubject(false);
  onStart() {
    this.isLoading$.next(true);
    setTimeout(() => this.isLoading$.next(false), 5000);
  }
}

host.component.ts

import { ChangeDetectionStrategy, Component } from '@angular/core';
import { BaseHostComponent } from './base-host.component';

@Component({
  selector: 'host',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <inner [bindIO]></inner>
  `
})
export class HostComponent extends BaseHostComponent {
  propA = 'Prop A: defined';
  propB = 'Prop B: defined';
}

Debug

For global debug all bindings

import { NgxBindIOModule } from 'ngx-bind-io';

@NgModule({
  ...
  imports: [
    ...
    NgxBindIOModule.forRoot({debug: true})
    ...
  ],
  ...
})
export class AppModule { }

For debug on one place

<comp-name [bindIO]="{debug:true}"></comp-name>

Rules for detect inputs and outputs

Custom rules for detect output method

my-ngx-bind-outputs.service.ts

import { Injectable } from '@angular/core';
import { IBindIO, NgxBindOutputsService } from 'ngx-bind-io';

@Injectable()
export class MyNgxBindOutputsService extends NgxBindOutputsService {
  checkKeyNameToOutputBind(directive: Partial<INgxBindIODirective>, hostKey: string, innerKey: string) {
    const outputs = directive.outputs;
    const keyWithFirstUpperLetter =
      innerKey.length > 0 ? innerKey.charAt(0).toUpperCase() + innerKey.substr(1) : innerKey;
    return (
      (hostKey === `on${keyWithFirstUpperLetter}` &&
        outputs.hostKeys.indexOf(`on${keyWithFirstUpperLetter}Click`) === -1 &&
        outputs.hostKeys.indexOf(`on${keyWithFirstUpperLetter}ButtonClick`) === -1) ||
      (hostKey === `on${keyWithFirstUpperLetter}Click` &&
        outputs.hostKeys.indexOf(`on${keyWithFirstUpperLetter}ButtonClick`) === -1) ||
      hostKey === `on${keyWithFirstUpperLetter}ButtonClick`
    );
  }
}

app.module.ts

import { NgxBindOutputsService, NgxBindIOModule } from 'ngx-bind-io';
import { MyNgxBindOutputsService } from './shared/utils/my-ngx-bind-outputs.service';
import { InnerComponent } from './inner.component';
import { HostComponent } from './host.component';

@NgModule({
  declarations: [AppComponent],
  imports: [
    ...
    NgxBindIOModule,
    ...
  ],
  declarations: [
    AppComponent,
    InnerComponent,
    HostComponent,
    ...
  ],
  providers: [
    ...
    { provide: NgxBindOutputsService, useClass: MyNgxBindOutputsService },
    ...
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Default rules for detect output method

ngx-bind-outputs.service.ts

export class NgxBindOutputsService {
  ...
  checkKeyNameToOutputBind(directive: Partial<INgxBindIODirective>, hostKey: string, innerKey: string) {
    const outputs = directive.outputs;
    const keyWithFirstUpperLetter = innerKey.length > 0 ? innerKey.charAt(0).toUpperCase() + innerKey.substr(1) : innerKey;
    return (
      (hostKey === `on${keyWithFirstUpperLetter}` &&
        outputs.hostKeys.indexOf(`on${keyWithFirstUpperLetter}Click`) === -1) ||
      hostKey === `on${keyWithFirstUpperLetter}Click`
    );
  }
  ...
}

Default rules for detect inputs variables

ngx-bind-inputs.service.ts

export class NgxBindInputsService {
  ...
  checkKeyNameToInputBind(directive: Partial<INgxBindIODirective>, hostKey: string, innerKey: string) {
    return hostKey === innerKey && hostKey[0] !== '_';
  }
  ...
  checkKeyNameToObservableInputBind(directive: Partial<INgxBindIODirective>, hostKey: string, innerKey: string) {
    return hostKey === `${innerKey}$` && hostKey[0] !== '_';
  }
  ...
}

Bind to dynamic components

Becouse dynamic components not have normal lifecicle, recomendate define they without OnPush strategy.

If you want use with OnPush, you may use Inputs with BindObservable and call properties with async pipe.

Or use NgxBindIoService and run method linkHostToInner for bind inputs and outputs.

inner.component.ts

import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { BindIoInner } from 'ngx-bind-io';

@BindIoInner() // <-- need for correct detect manual inputs like [propName]="propValue"
@Component({
  selector: 'inner',
  // changeDetection: ChangeDetectionStrategy.OnPush, <-- change detection with OnPush strategy incorrected work for dynamic components
  template: `
    <div *ngIf="isLoading">Loading... (5s)</div>
    <button (click)="onStart()">Start</button> <br />
    {{ propA }} <br />
    {{ propB }}
  `
})
export class InnerComponent {
  @Input()
  isLoading: boolean = undefined;
  @Input()
  propA = 'Prop A: not defined';
  @Input()
  propB = 'Prop B: not defined';
  @Output()
  start = new EventEmitter();
  onStart() {
    this.start.next(true);
  }
}

host.component.ts

import { ChangeDetectionStrategy, ChangeDetectorRef, Component, SkipSelf } from '@angular/core';
import { BaseHostComponent } from './base-host.component';
import { BehaviorSubject } from 'rxjs';
import { InnerComponent } from './inner.component';

@Component({
  selector: 'host',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <template #inner></template>
  `
})
export class HostComponent {
  @ViewChild('inner', { read: ViewContainerRef })
  inner: ViewContainerRef;

  propA = 'Prop A: defined';
  propB = 'Prop B: defined';
  isLoading$ = new BehaviorSubject(false);

  constructor(
    private _ngxBindIoService: NgxBindIoService,
    @SkipSelf()
    private _parentInjector: Injector,
    private _changeDetectorRef: ChangeDetectorRef,
    private _resolver: ComponentFactoryResolver
  ) {
    this.createInner();
  }
  createInner() {
    this.inner.clear();
    const factory = this._resolver.resolveComponentFactory(InnerComponent);
    const componentRef = this.inner.createComponent(factory);
    this._ngxBindIoService.linkHostToInner(
      this,
      componentRef.instance,
      { propA: this.propA, propB: this.propB },
      this._parentInjector,
      this._changeDetectorRef
    );
  }
  onStart() {
    this.isLoading$.next(true);
    setTimeout(() => this.isLoading$.next(false), 5000);
  }
}

Work without IVY Renderer

For correct work without IVY Renderer, all inner Inputs, Outputs and all host properties ​​must be initialized, you can set them to "undefined".

For check project ready to use bindIO directives, you may use ngx-bind-io-cli and run:

npx ngx-bind-io-cli ./src --maxInputs=0 --maxOutputs=0

For check and add initialize statement:

npx ngx-bind-io-cli ./src --fix=all --maxInputs=0 --maxOutputs=0

For check and add initialize statement if you want correct work with tspath:

npx ngx-bind-io-cli ./src --fix=all --maxInputs=0 --maxOutputs=0  --tsconfig=./src/tsconfig.app.json

License

MIT

changelog

1.0.1 (2020-03-14)

Bug Fixes

  • incorrect detect components without ivy mode (b8e5158)

1.0.0 (2020-03-14)

Features

  • add support get inputs and outputs from ivy metadata (e6e4f3d)

0.7.0 (2020-03-13)

Features

  • update deps and all sources for it, update to Angular9 ivy (751c243)

0.6.6 (2019-04-03)

Bug Fixes

  • Add runnedFromBindIo attribute to ngOnChanges and ngOnDestroy, for detect and stop twiced run (e870a97)

0.6.5 (2019-02-11)

Bug Fixes

  • Remove enable debug with set "debug_ngx-bind-io" to "true" in localStorage (55167fd)

0.6.4 (2019-02-05)

Bug Fixes

  • Remove wrong bind value (c933f3d)

0.6.3 (2019-02-04)

Bug Fixes

  • Update logic of binding inputs and outputs for correct work on dynamic components (97bae1f)

0.6.2 (2019-02-04)

Bug Fixes

  • Update decorators for correct call originalNgOnChanges (a3334db)

0.6.1 (2019-02-03)

Bug Fixes

  • Remove create on host component all "inputs" needed for correct work inner component, if them not exists (d65303f)

0.6.0 (2019-02-02)

Bug Fixes

  • Update words for removeKeysNotAllowedConstants (8846b66)

Features

  • Add support binding to dynamic created components (d8f07f4)

0.5.3 (2019-02-02)

Bug Fixes

  • Add create on host component all "inputs" needed for correct work inner component, if them not exists (f1e8aa7)

0.5.2 (2019-02-01)

Bug Fixes

0.5.1 (2019-01-30)

Bug Fixes

  • Add support send changes to user defined ngOnChanges methods (7f72996)

0.5.0 (2019-01-29)

Bug Fixes

  • Update naming: parent=>host, child=>inner (ba8cb48)

Features

  • Add BindIoInner() decorator for detect and use manual inputs, and support detect and use manual outputs (82e8a69)

0.4.1 (2019-01-27)

Bug Fixes

  • Add includeIO and excludeIO properties for directives (3e44423)
  • Change detect native attributes, remove replace ngreflect (not work in prod build) (2e0423f)
  • Update checkKeyNameToObservableInputBind for ignore private variables (28660c2)

0.4.0 (2019-01-27)

Features

  • Tested on big application, and fix: bind one host to many inner components, add ignore inputs and outputs binded with html attributes (6fdd5b8)

0.3.0 (2019-01-25)

Bug Fixes

  • Remove type check of child component inputs and outputs (c5a067c)

Features

  • Add debug options for show in dev mode warnings with not initialized inputs or outputs (7a317e3)
  • Add support set options of INgxBindIOConfig interface to directives for local debug bindings, example: <comp [bindIO]="{debug:true}"></comp> (ba59661)

0.2.0 (2019-01-21)

Features

  • Add support update inputs values on child component, when update values in parent component (d55460e)

0.1.1 (2019-01-20)

Bug Fixes

  • Add prefix for detect used inputs and outputs (03d8acd)
  • Trim used array to usedInputs and usedOutputs (ebbfb16)

0.1.0 (2019-01-20)

Features