如何在Angular中声明对象数组?

527 阅读2分钟

这个例子涵盖了Angular在typecript中的例子

  • 声明并初始化带值的对象数组
  • 类型的数组
  • 使用接口来保存对象数组

对象数组被填充并显示在Dropdown或radio button上。

我们有多种方法可以创建一个对象数组

如何声明和初始化带值的对象数组

使用any/object 类型声明和初始化数组,声明如下

对象是包含键和值的属性,在Typescript和angular中没有类型来表示对象。

字符串数组可以用下面的语法来声明和初始化

private arrays:Array = ['one','two','three'];

在typescript中,对象可以用any 类型来声明:

  public books: Array = [
    { title: "book1", description: "book desc 1" },
    { title: "book2", description: "book desc 2" },
    { title: "book3", description: "book desc 3" },
    { title: "book4", description: "book desc 4 " }
  ];

同样可以用对象类型代替任何类型

    public books: Array = [
    { title: "book1", description: "book desc 1" },
    { title: "book2", description: "book desc 2" },
    { title: "book3", description: "book desc 3" },
    { title: "book4", description: "book desc 4 " }
  ];
Array of type alias object In Angular using type keyword in typescript allows to create new alias for custom type. Created employee object alias and created array of type alias. type Employee = Array<{ id: number; name: string }>;
IN the below example  Created employee alias of array type Initialized array with object values  import { Component, OnInit } from "@angular/core";

@Component({
  selector: "app-basic",
  templateUrl: "./basic.component.html",
  styleUrls: ["./basic.component.css"]
})
export class BasicComponent implements OnInit {
  employees: Employee = [
    { id: 1, name: "Ram" },
    { id: 2, name: "John" },
    { id: 3, name: "Franc" },
    { id: 4, name: "Andrew " }
  ];
  constructor() {}

  ngOnInit() {}
}
type Employee = Array<{ id: number; name: string }>;


  {{emp.name}}

The same syntax can be rewritten using shorter version const employees: Array<{id: number, name: string}> = [
    { id: 1, name: "Ram" },
    { id: 2, name: "John" },
    { id: 3, name: "Franc" },
    { id: 4, name: "Andrew " }
  ];

declare array of objects using interface type The above approach has some drawbacks if object contains multiple properties and it is very difficult to handle This approach is to create a interface to hold object data in angular and typescript codebase. This is very useful handle data coming from backend/Database via REST API’s You can create interface using below command It generates book.ts file export interface Book {
  id: number;
  name: string;

  constructor(id,name) {
      this.id = id;
      this.name = name;
    }
}
In Angular typescript component, You can create an interface Book import { Component, OnInit } from "@angular/core";
import {Book} from './Book'
@Component({
  selector: "app-basic",
  templateUrl: "./basic.component.html",
  styleUrls: ["./basic.component.css"]
})
export class BasicComponent implements OnInit {
  public books: Book[] = [
    { id: 1, name: "Book 1" },
    { id: 2, name: "Book 2" },
    { id: 3, name: "Book 3" },
    { id: 4, name: "Book 4 " }
  ];
  constructor() {}

  ngOnInit() {}
}