简体   繁体   English

在Angular中的参数周围花括号

[英]Curly braces around a parameter in Angular

Looking at some Angular code: 看一些Angular代码:

    @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. 当我尝试在Angular的上下文中使用参数谷歌花括号/小胡子时,找不到太多结果。 What effect is achieved by wrapping a parameter in curly braces in Angular? 通过将参数包装在Angular中的花括号中会产生什么效果?

Thanks. 谢谢。

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: 您有一个函数可以打印出传递给它的对象的age

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: 此函数使用整个对象-但是,由于实际上不需要该对象的其他属性(仅age ),因此可以使用解构来提取该属性:

function printAge({ age }) {
    console.log(age);
}

This is ES6 shorthand for the following: 这是ES6的简称:

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: 这是ES5:

public editHandler(item) {
    var dataItem = item.dataItem;
    this.editDataItem = dataItem;
    this.isNew = false;
}

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. 并将其传递给一个函数,在ES6中,我们可以像下面的对象一样直接传递一个对象。

public editHandler({test: "test"}) { 
        this.editDataItem = test;
        this.isNew = false;
    }

curly braces are nothing but an object. 大括号不过是一个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM