A simple way to set default values to your component inputs and properties using a decorator.
🚀 See it in action on Stackblitz
yarn add @katze/ngx-input-default-value
or
npm install @katze/ngx-input-default-value --save
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' }
}
}
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' }