In Angular, how to handle the case where a setter depends on an input?

Viewed 33

I have two @Input props, and I want to monitor one of them, and do something everytime it changes.

However, this "do something" is dependent on another @Input.

For example

  // This is the 1st input prop, which is monitored using a setter
  private _inputOne: string;

  @Input() set inputOne(value: string) {
    this._inputOne= value;

    // Whether the setter needs to do something depends on another input called "inputTwo"
    if (this.inputTwo) {
        ... do something
    }
  }

  get _inputOne(): string {
    return this._inputOne;
  }

  // This is the 2nd input prop.
  @Input() inputTwo: boolean;

The problem is that, the setter set inputOne(value: string) seems to have no access to the other input inputTwo. From its POV, inputTwo is always undefined, but it really needs its actual value.

I am wondering how to solve this issue...

Maybe I can pass in both of them from the parent component everytime only inputOne is changed, then use the ngOnChanges hook, because it has access to both of them, but is there a more elegant solution?

Thanks in advance!

1 Answers

You shouldn't rely on the order those Inputs are set. You could wait for a Promise that is resolved in the ngOnInit hook. ngOnInit is called after the Inputs are set.

@Component(/* ... */)
class MyComponent implements OnInit {
    private _inputOne: string;

    @Input()
    public set inputOne(value: string) {
        this._inputOne = value;
        this.onInitCalled.then(() => {
            if (this.inputTwo) {
                // do something
            }
        });
    }
    public get inputOne(): string { return this._inputOne; }
    @Input() public inputTwo: boolean;

    private onInit = new Subject<void>();
    private onInitCalled = firstValueFrom(this.onInit);
    ngOnInit() {
        this.onInit.next();
        this.onInit.complete();
    }
}

Or you could just replace your "do something" with a function call, skip it if inputTwo is undefined and call the function from your ngOnInit hook.

Related