1

I've noticed that @Input setter in a Directive is not initially called when in the template a value of an empty string ("") is provided. But when the value of "null" or "false" is provided, the setter method is called.

Why is that?

As far as I've read, an empty string is a falsy value in JS, so why passing an empty string does not work as "null" or "false"? Is it a feature?

DIRECTIVE:

@Directive({
  selector: '[myInputDir]'
})

export class ExampleDirectiveClass {
  @Input('myInputDir') public set valFromMyInput(value: string) {
    if (value) {
      this._inputVal = value;
    } else {
      this._inputVal = 'setUpVal';
    }
  }
(... rest of the class)
}

HTML

(...)
<input
  [myInputDir]="">
</input>
(...)
2
  • I suspect it is because empty string ("") is take it as default value of string Commented Sep 11, 2020 at 10:14
  • The answers given by Mat-Dob-Dev and user3548205 are valid. Basically, when not providing anything, undefined is "provided". And it seems that undefined, even if it is a falsy value, does not trigger a setter. Commented Sep 15, 2020 at 9:53

2 Answers 2

3

In given example you're not providing empty string. You're not providing any value at all (thus setter has not been called).

Invalid example (no value at all):

<input
  [myInputDir]="">
</input>

Valid example of providing empty string as input value:

<input
  [myInputDir]="''">
</input>

The square brackets around input name tell Angular to evaluate the template expression inside quotation marks.

Sign up to request clarification or add additional context in comments.

Comments

1

The variable you want to pass to the attribute is missing. You donate nothing, which is undefined.

<input
  [myInputDir]="putAnyVariableHere">
</input>

1 Comment

Yes, it makes sense. It's so simple.. I guess, when writing this question, I've "forgotten" that it's HTML and empty quotation marks just don't hold any value themselves.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.