Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: How to get default @Input value?

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!

like image 640
Fabian Avatar asked Nov 04 '19 15:11

Fabian


People also ask

What is @input set in Angular?

Use the @Input() decorator in a child component or directive to let Angular know that a property in that component can receive its value from its parent component. It helps to remember that the data flow is from the perspective of the child component.

What is @input and @output in Angular 2?

The @Input decorator binds a property within one component (child component) to receive a value from another component (parent component). This is one-way communication from parent-to-child. The component property should be annotated with @Input decorator to act as input property.


1 Answers

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;
like image 120
Poul Kruijt Avatar answered Nov 05 '22 19:11

Poul Kruijt