How to pass data from parent to child components?

7.1k Views Asked by At

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

2

There are 2 best solutions below

1
On BEST ANSWER

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 {{ ... }}.)

1
On

Try to remove the double parenthesis from the binding.

Instead of this :

[submitButtonDisabled]="{{disableSubmitButton()}}"

Use this :

[submitButtonDisabled]="disableSubmitButton()"

Or this :

submitButtonDisabled="{{disableSubmitButton()}}"