Is there any way to set the Input required conditionally in angular?

199 Views Asked by At

What I'm trying to achieve is having a component/directive input required only when another input is given, for example:

@Input() name!:string; 
@Input({ required: name!!}) surname!:string;

Is this possible?

I tried to set required: name!! but it doesn't work as intended, the only fields I potentially have access to are static fields

2

There are 2 best solutions below

0
Matthieu Riegler On

This is not possible, you can refer to this in the decorators.

Also keep in mind that required inputs are a compiler only feature. This information doesn't make it into the runtime bundles.

0
Fabio On

This way that you show is not possible but if i have understood good your purpose, to achieve your goal you can use getter and setter to check when required input data is valued inside your angular child component. For Example:

    private _name: string;

public get name(): string {
  return this._name;
}
@Input() public set name(value: string) {
  if (value) {
    // you can assign the value that come in input
    this._name = value;
  }
  else {
    // example: show a toast message error if !value
  }
}