6

We are developing components and when using them, we would like to use the same mechanism like for DOM nodes to conditionally define attributes. So for preventing attributes to show up at all, we set the value to null and its not existing in the final HTML output. Great!

<button [attr.disabled]="condition ? true : null"></button>

Now, when using our own components, this does not work. When we set null, we actually get null in the components @Input as the value. Any by default set value will be overwritten.

...
@Component({
    selector: 'myElement',
    templateUrl: './my-element.component.html'
})

export class MyElementComponent {
    @Input() type: string = 'default';
...
<myElment [type]="condition ? 'something' : null"></myElement>

So, whenever we read the type in the component, we get null instead of the 'default' value which was set.

I tried to find a way to get the original default value, but did not find it. It is existing in the ngBaseDef when accessed in constructor time, but this is not working in production. I expected ngOnChanges to give me the real (default) value in the first change that is done and therefore be able to prevent that null is set, but the previousValue is undefined.

We came up with some ways to solve this:

  • defining a default object and setting for every input the default value when its null
  • addressing the DOM element in the template again, instead of setting null
<myElement #myelem [type]="condition ? 'something' : myelem.type"></myElement>
  • defining set / get for every input to prevent null setting
_type: string = 'default';
@Input()
set type(v: string) {if (v !== null) this._type = v;}
get type() { return this._type; }

but are curious, if there are maybe others who have similar issues and how it got fixed. Also I would appreciate any other idea which is maybe more elegant.

Thanks!

Fabian
  • 301
  • 3
  • 7
  • possible duplicate of https://stackoverflow.com/questions/35839120/how-to-set-default-parameter-for-input-in-angular2 and https://stackoverflow.com/questions/36071942/how-to-set-default-values-for-angular-2-component-properties – Naga Sai A Nov 04 '19 at 15:36

3 Answers3

4

There is no standard angular way, because many times you would want null or undefined as value. Your ideas are not bad solutions. I got a couple more

  1. I suppose you can also use the ngOnChanges hook for this:
@Input()
type: string = 'defaultType';

ngOnChanges(changes: SimpleChanges): void {
 // == null to also match undefined
 if (this.type == null) {
    this.type = 'defaultType';
  }
}
  1. Or using Observables:
private readonly _type$ = new BehaviorSubject('defaultType');

readonly type$ = this._type$.pipe(
  map((type) => type == null ? 'defaultType' : type)
); 

@Input()
set type(type: string) {
  this._type$.next(type);
}
  1. Or create your own decorator playground
function Default(value: any) {
  return function(target: any, key: string | symbol) {
    const valueAccessor = '__' + key.toString() + '__';

    Object.defineProperty(target, key, {
      get: function () {
        return this[valueAccessor] != null ? this[valueAccessor] : value
      },
      set: function (next) {
        if (!Object.prototype.hasOwnProperty.call(this, valueAccessor)) {
          Object.defineProperty(this, valueAccessor, {
            writable: true,
            enumerable: false
          });
        }

        this[valueAccessor] = next;
      },
      enumerable: true
    });
  };
}

which you can use like this:

@Input()
@Default('defaultType')
type!: string;
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
  • The third solution looks very promising. Unfortunatelly it is not working as soon you have a component more than one time. All components will receive the same type set from outside, even if some or one got null he will get the type from the other component. As this looks the most promising I will look further into it and see where is ( i made ) the mistake :) Thanks! – Fabian Nov 08 '19 at 13:40
  • @Fabian I should not have posted untested code :) anyways, I've updated my answer. We obviously need to use a value accessor property, so that it's different for every instance. – Poul Kruijt Nov 08 '19 at 14:37
  • I got already a working version together by myself, thanks a lot for the update. Now it works like a charm! ;) Thank you for the idea of creating own decorators. – Fabian Nov 11 '19 at 08:03
  • @Fabian You're welcome :) how did you manage to make it work for multiple class instances? – Poul Kruijt Nov 11 '19 at 08:40
  • @Fabian I've updated my answer a bit from the decorator, because I noticed that in a `for .. in` loop it would show the value accessor property as well. By declaring it directly in the `this.set` and setting enumerable to false it won't show up anymore. – Poul Kruijt Nov 11 '19 at 09:04
  • I took the decorator approach, check my [stackblitz example](https://stackblitz.com/edit/default-value-decorator) with decorator tests – ndraiman Jul 26 '20 at 09:24
  • @Nexaddo your decorator will fail when you have two components with different values. I've forked your stackblitz [here](https://stackblitz.com/edit/default-value-decorator-mbyhgi?file=src%2Fapp%2Fapp.component.html). As you can see, the undefined gets overwritten with the set value of the 2nd component. I first had it like you had, but had to change it to use a hidden `valueAccessor` value :) – Poul Kruijt Jul 26 '20 at 10:48
  • You're correct, the issue seems to be due to the fact that property decorators get initialised only once per the entire app and not per class. so the `val` variable in the decorator will hold only the last changed value. We need the class to hold the value for this to work. Thank you for the feedback @PoulKruijt, I updated my [stackblitz example](https://stackblitz.com/edit/default-value-decorator) with a new test to check for this issue – ndraiman Jul 27 '20 at 08:51
0

Just one more option (perhaps simpler if you don't want to implement your own custom @annotation) based off Poul Krujit solution:

const DEFAULT_VALUE = 'default';
export class MyElementComponent {
  typeWrapped = DEFAULT_VALUE;

  @Input()
  set type(selected: string) {
    // this makes sure only truthy values get assigned
    // so [type]="null" or [type]="undefined" still go to the default.
    if (selected) {
      this.typeWrapped = selected;
    } else {
      this.typeWrapped = DEFAULT_VALUE;
    }
  }
  get type() {
    return this.typeWrapped;
  }
}
Tom Roggero
  • 5,777
  • 1
  • 32
  • 39
  • 1
    the issue with this, if you first have a value on the input, and then set this value to `null` or `undefined` it won't change the `typeWrapped` property, and your default value is gone. – Poul Kruijt Nov 23 '20 at 19:34
  • I've updated my proposal to include that case. – Tom Roggero Dec 04 '20 at 12:33
-1

If you need to do this for multiple inputs, you can also use a custom pipe instead of manually defining the getter/setter and default for each input. The pipe can contain the logic and defaultArg to return the defaultArg if the input is null.

i.e.

// pipe
@Pipe({name: 'ifNotNullElse'})
export class IfNotNullElsePipe implements PipeTransform {
  transform(value: string, defaultVal?: string): string {
    return value !== null ? value : defaultVal;
  }
}
<!-- myElem template -->
<p>Type Input: {{ type | ifNotNullElse: 'default' }}</p>

<p>Another Input: {{ anotherType | ifNotNullElse: 'anotherDefault' }}</p>
christian
  • 1,585
  • 1
  • 11
  • 13