Search code examples
angulartypescriptangular2-componentsangular2-databinding

How to pass data from parent to child components?


I have this property in a child component:

@Input() submitButtonDisabled: boolean;

In the template of my parent component I set it via property binding using interpolation:

<my-child-component
  [submitButtonDisabled]="{{disableSubmitButton()}}">
</my-child-component>

The child component template reads its submitButtonDisabled property this way:

<button id="btSubmit" type="submit" (click)="submit()" 
  [disabled]="submitButtonDisabled">Ok</button>

Debugging my typescript code I see property binding working fine, but the submit button keeps disabled no matter what disableSubmitButton returns (a boolean value). It seems the component is being rendered before the binding to take place.

Does this make any sense? Where is my mistake?

Reference: Angular 2 - Component Communication


Solution

  • If you're passing a string literal to your input property, DO NOT USE the square brackets:

    <my-comp isDisabled="yes"></my-comp>
    <my-comp isDisabled="no"></my-comp>
    

    In this example, the input property isDisabled will contain the string 'yes' or 'no'.

    If you're passing anything other than a string literal, then you MUST use the square brackets:

    <my-comp [isDisabled]="true"></my-comp>
    <my-comp [isDisabled]="false"></my-comp>
    <my-comp [isDisabled]="shouldItBeDisabled()"></my-comp>
    

    In that example, the input property isDisabled will contain the boolean true or false, or the value returned by the shouldItBeDisabled() method.

    Notice how NONE of these scenarios uses {{ ... }}.

    In your case, the problem might be that your method disableSubmitButton() doesn't return the correct value. (Also, like Ron537 said, you should drop the {{ ... }}.)