Search code examples
angularangular2-components

How to set Angular2 component input conditionally?


Consider the following case.

Parent component:

<div title="title1">
  <my-component input="title2"></my-component>
  <my-component></my-component>
</div>

MyComponent:

<div [title]="input">ABC</div>

The problem here is that first "ABC" div will have the "title2" tooltip while the second one will have whatever MyComponent has as default value for input, and this will "override" "title1" tooltip which is not desired.

How can I avoid setting "title" in MyComponent template if no "input" is received?


Solution

  • It appears that binding the title property of the child element will override the parent title, even when input is null or undefined. However, according to this stackblitz, binding the title attribute with [attr.title] allows to inherit the parent title when input is null or undefined:

    <div [attr.title]="input">ABC</div>
    

    with

    @Input() input: string; // undefined by default