在Angular 2中,可以使用自定义键字段创建对象映射。以下是一个使用自定义键字段创建对象映射的示例代码:
interface MyObject {
id: number;
name: string;
customKey: string;
}
myObjectMap: { [key: string]: MyObject } = {};
addObjectToMap() {
const newObj: MyObject = {
id: 1,
name: 'Object 1',
customKey: 'key1'
};
this.myObjectMap[newObj.customKey] = newObj;
}
getObjectFromMap() {
const customKey = 'key1';
const obj = this.myObjectMap[customKey];
console.log(obj);
}
通过以上步骤,您可以使用自定义键字段创建对象映射并访问其中的对象。