Reputation: 1517
Looking at some Angular code:
@Component({
selector: 'my-app',
templateUrl: 'kendoGrid.component.html'
})
export class AppComponent implements OnInit {
public editDataItem: Product;
public isNew: boolean;
private editService: EditService;
public editHandler({dataItem}) { // What does wrapping a parameter in curly braces do?
this.editDataItem = dataItem;
this.isNew = false;
}
}
I could not find much result when I try to google curly braces / moustache with parameter in the context of Angular. What effect is achieved by wrapping a parameter in curly braces in Angular?
Thanks.
Upvotes: 2
Views: 1385
Reputation: 44125
It's known as destructuring, and it works like so:
Say you have an object which contains a person's name and age:
const person = {
name: "John Doe",
age: 42
};
And you have a function which prints out the age
of the object passed to it:
function printAge(obj) {
console.log(obj.age);
}
This function uses the whole object - however, since we don't actually need the other properties of the object (only age
) we can use destructuring to extract that property:
function printAge({ age }) {
console.log(age);
}
This is ES6 shorthand for the following:
function printAge(obj) {
var age = obj.age;
console.log(age);
}
So, all that this function does:
public editHandler({ dataItem }) {
this.editDataItem = dataItem;
this.isNew = false;
}
Is this ES5:
public editHandler(item) {
var dataItem = item.dataItem;
this.editDataItem = dataItem;
this.isNew = false;
}
Upvotes: 5
Reputation: 2166
Instead of adding an object like
const dataItem = {test: "test"};
and pass it to a function, in ES6 we can directly pass an object like the one below.
public editHandler({test: "test"}) {
this.editDataItem = test;
this.isNew = false;
}
curly braces are nothing but an object.
Upvotes: -1