Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement two-way data binding for custom property

I see in primeng components the use something like ngModel (two-way data binding) style for some property like this

[(selection)]="selectedItem";

it 's look like

@Input() selection;
@Output() selection:EventEmitter<any> = new EventEmitter<any>();

how I can implement something like this and is it possible to do for more than single property like

 <component-a  [(selection)]="selectedItem"  [(data)]="selectedData"></component-a>
like image 531
Muhammed Albarmavi Avatar asked Sep 12 '18 08:09

Muhammed Albarmavi


People also ask

How is 2 way data binding implemented?

For two-way data binding, declare a private property and access its value using get and set methods in the component class. Then, assign that property to [(ngModel)] . For example, declare a private property with a get and set method, as shown below. Now, assign userName to [(ngModel)] in the template.

Which module is needed to implement two-way data binding?

Two-way data binding can be achieved using a ngModel directive in Angular. The below syntax shows the data binding using (ngModel), which is basically the combination of both the square brackets of property binding and parentheses of the event binding.

Which are 2 types of data binding?

AngularJS provides two types of Data Binding: One-way data binding. Two-way data binding.

What is custom property binding in Angular?

Property binding in Angular helps you set values for properties of HTML elements or directives. Use property binding to do things such as toggle button features, set paths programmatically, and share values between components.


1 Answers

Angular docs

<app-sizer 
  [(size)]="fontSizePx">
</app-sizer>

The two-way binding syntax is really just syntactic sugar for a property binding and an event binding. Angular desugars the binding into this:

<app-sizer
  [size]="fontSizePx"
  (sizeChange)="fontSizePx=$event">
</app-sizer>

To create two-way binding for property selection use:

@Input() selection;

// You have to follow this convention (For Output property)
// i.e. <propertyName><Change> like selectionChange

@Output() selectionChange:EventEmitter<any> = new EventEmitter<any>();

And to change selection in component as shown below:

changeSelection(newSelection)
{
    this.selection = newSelection;

    // emit change event to parent component
    this.selectionChange.emit(this.selection);  
}
like image 124
Buggy Avatar answered Oct 22 '22 08:10

Buggy