如何通过Syncfusion的getSelectedRecords()访问JS对象元素
getSelectedRecords() in Angular 7 Hey there! I totally get where you're coming from—when you call getSelectedRecords(), it returns an Object[], so TypeScript doesn't recognize the specific fields on those objects, which is why direct dot notation like .元素名 doesn't work. Let's fix this with a couple of straightforward, practical approaches.
1. Define a Type Interface (Recommended for Type Safety)
First, create an interface that matches the structure of your grid data. This tells TypeScript exactly what fields each record contains, enabling proper type checking and autocompletion:
// Define an interface that mirrors your grid's data structure interface Order { OrderID: number; CustomerID: string; ShipCity: string; ShipName: string; }
Then, in your component, cast the result of getSelectedRecords() to an array of this interface. This lets you safely access fields with dot notation:
rowSelected(args: RowSelectEventArgs) { // Cast selected records to your custom interface array let selectedrecords: Order[] = this.grid.getSelectedRecords() as Order[]; if (selectedrecords.length > 0) { // Get specific field values from the first selected record const firstOrderId = selectedrecords[0].OrderID; const firstCustomerId = selectedrecords[0].CustomerID; // Store values in typed variables const orderIdVar: number = firstOrderId; const customerIdVar: string = firstCustomerId; console.log('Selected Order ID:', orderIdVar); console.log('Selected Customer ID:', customerIdVar); // Loop through all selected records if needed selectedrecords.forEach(record => { console.log('Ship City:', record.ShipCity); }); } }
2. Quick Fix: Type Assertion to any
If you don't want to create an interface right now, you can cast individual records to any to bypass TypeScript's type checks temporarily:
rowSelected(args: RowSelectEventArgs) { let selectedrecords: Object[] = this.grid.getSelectedRecords(); if (selectedrecords.length > 0) { // Cast the first record to 'any' to access fields directly const selectedRecord = selectedrecords[0] as any; const shipName: string = selectedRecord.ShipName; console.log('Selected Ship Name:', shipName); } }
3. Bracket Notation (No Type Safety)
You can also use bracket notation to access fields, though this skips TypeScript's type validation:
rowSelected(args: RowSelectEventArgs) { let selectedrecords: Object[] = this.grid.getSelectedRecords(); if (selectedrecords.length > 0) { const shipCity: string = selectedrecords[0]['ShipCity']; console.log('Selected Ship City:', shipCity); } }
The interface approach is the best long-term solution because it keeps your code type-safe and helps catch errors early. All these methods will let you extract specific field values into variables of the correct type, just like you need.
内容的提问来源于stack exchange,提问作者E.Anna

