'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?
Solution 1:[1]
I believe the best you can do is this:
(subProperty)="mainProperty = $event"
Solution 2:[2]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | delashum |
| Solution 2 | John |
