Superman.Lopez
Superman.Lopez

Reputation: 1600

In Angular, can I bind the emited output of a component directly to a property?

My main application component interacts with sub components through @Output decorated properties on the subcomponent. The output properties use and EventEmitter<>(). Often the property emits a simple boolean or number. I would like to bind this output directly to properties in the main application. But am failing to do so.

What I am doing at the moment is:

//In my sub component:
@Output() subProperty = new EventEmitter<boolean>();

//In my main template:
<sub-component (subProperty)="setPropertyValue($event)"></subcomponent>

//In my main component (this I would like to avoid):
setPropertyValue(event) {
    this.mainProperty = event;
}

What I wanted to do was avoid the function in my main component and bind directly to my property, but the below code doesn't work:

//In my sub component:
@Output() subProperty = new EventEmitter<boolean>();

//In my main template:
<sub-component (subProperty)="mainProperty"></subcomponent>

Is there anyway I can avoid the additional function in my main component?

Upvotes: 2

Views: 1057

Answers (2)

John
John

Reputation: 31

Add the suffix Change to the end of your property so you can use the banana/football in the box syntax. A matching input is not required and will be ignored.

//In your sub component:
@Output() subPropertyChange = new EventEmitter<boolean>();
//In your main template:
<sub-component [(subProperty)]="mainProperty"></subcomponent>

Upvotes: 1

delashum
delashum

Reputation: 821

I believe the best you can do is this:

(subProperty)="mainProperty = $event"

Upvotes: 6

Related Questions