Skip to content

✨ Decorator that set default values to your component inputs and properties

Notifications You must be signed in to change notification settings

ZeevKatz/ngx-input-default-value

Repository files navigation

npm npm Build Status

Angular | Default value for inputs and properties️ ⚡

A simple way to set default values to your component inputs and properties using a decorator.

🚀 See it in action on Stackblitz


Installation

yarn add @katze/ngx-input-default-value

or

npm install @katze/ngx-input-default-value --save

Usage

import { Component, ChangeDetectionStrategy, OnChanges, SimpleChanges, Input } from '@angular/core';
import { InputDefaultValue } from '@katze/ngx-input-default-value';

type SimpleObject = { bar: string, foo: string };

@Component({
  selector: 'simple-component',
  templateUrl: './simple-component.component.html',
  styleUrls: ['./simple-component.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class SimpleComponent implements OnChanges {
  @Input()
  @InputDefaultValue<SimpleObject>({
    bar: 'Default bar value',
    foo: 'Default foo value'
  })
  simpleObject: Partial<SimpleObject>;
  
  ngOnChanges(changes: SimpleChanges) {
    // In case: 
    // <simple-component></simple-component>
    this.simpleObject; // => { bar: 'Default bar value', foo: 'Default foo value' }
    
    // In case: 
    // <simple-component [simpleObject]="{bar: 'New bar value'}"></simple-component>
    this.simpleObject; // => { bar: 'New bar value', foo: 'Default foo value' }
  }
}

Use with any class

import { InputDefaultValue } from '@katze/ngx-input-default-value';

type SimpleObject = { bar: string, foo: string };

class SimpleClass {
  @InputDefaultValue<SimpleObject>({
    bar: 'Default bar value',
    foo: 'Default foo value'
  })
  simpleObject: Partial<SimpleObject>;
}

const instance = new SimpleClass();

instance.simpleObject;
// => { bar: 'Default bar value', foo: 'Default foo value' }

instance.simpleObject = {
  bar: 'New bar value'
};

instance.simpleObject;
// => { bar: 'New bar value', foo: 'Default foo value' }

instance.simpleObject = null;

instance.simpleObject;
// => { bar: 'Default bar value', foo: 'Default foo value' }

About

✨ Decorator that set default values to your component inputs and properties

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published