Coder Social home page Coder Social logo

endykaufman / ngx-bind-io Goto Github PK

View Code? Open in Web Editor NEW
9.0 2.0 2.0 6.35 MB

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

Home Page: https://endykaufman.github.io/ngx-bind-io/

License: MIT License

JavaScript 1.21% TypeScript 79.23% HTML 18.11% CSS 1.25% Shell 0.20%
input output directives dynamic auto bind binding inheritance hierarchy nested

ngx-bind-io's Introduction

ngx-bind-io

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

Links

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';

@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;
  @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';

@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

inner.component.ts

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

@BindIoInner() // <-- need if use not IVY Renderer 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; // if use not IVY Renderer you mast define all inputs and outputs
  @Input()
  propA = 'Prop A: not defined';
  @Input()
  propB = 'Prop B: not defined';
  @Output()
  start = new EventEmitter();
  onStart() {
    this.start.next(true);
  }
}

License

MIT

ngx-bind-io's People

Contributors

endykaufman avatar greenkeeper[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

ngx-bind-io's Issues

An in-range update of karma-jasmine-html-reporter is breaking the build 🚨

The devDependency karma-jasmine-html-reporter was updated from 1.4.0 to 1.4.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

karma-jasmine-html-reporter is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • βœ… continuous-integration/travis-ci/push: The Travis CI build passed (Details).
  • ❌ Travis CI - Branch: The build errored.

Commits

The new version differs by 2 commits.

  • 83f51f0 Bump to 1.4.1
  • 828a932 fix: set specFilter only when needed (#24)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

⚠️ Greenkeeper is no longer available for new installations

Hello!

Greenkeeper is no longer available for new installations.

The service will be saying goodbye πŸ‘‹ and passing the torch to Snyk on June 3rd, 2020. Find out more at greenkeeper.io.

If this is your only Greenkeeper installation, you can just sign up for Snyk directly, it’s free for Open Source and even has free features for private projects as well.

Nevertheless, thanks for your interest in Greenkeeper! We’re sure your repositories will find a good home at Snyk β˜€οΈπŸ‘πŸ’œ

All the best from everyone at Greenkeeper! πŸ‘‹πŸ€–πŸŒ΄

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.