sourcetip

각진 배열에 항목 추가 4

fileupload 2023. 7. 2. 20:54
반응형

각진 배열에 항목 추가 4

다음 코드가 있습니다.

export class FormComponent implements OnInit {
  name: string;
  empoloyeeID : number;
  empList: Array<{name: string, empoloyeeID: number}> = []; 
  constructor() {
  }

ngOnInit() {
  }

onEmpCreate(){
   console.log(this.name,this.empoloyeeID);
   this.empList.push.apply(this.name,this.empoloyeeID);
   this.name ="";
   this.empoloyeeID = 0;
   }
}

하지만 이 던지기 실수.

개체가 아닌 다른 개체에 대해 ArrayLike에서 CreateList가 호출되었습니다.

또한 여기에 배열을 정의하는 대신 사용자 지정 클래스 및 사용자 지정 개체 목록을 만들 수 있는 방법이 있습니까?

감사해요.

네, 방법이 있습니다.

먼저 클래스를 선언합니다.

//anyfile.ts
export class Custom
{
  name: string, 
  empoloyeeID: number
}

그런 다음 구성 요소에서 클래스를 가져옵니다.

import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit {
 name: string;
 empoloyeeID : number;
 empList: Array<Custom> = [];
 constructor() {

 }

 ngOnInit() {
 }
 onEmpCreate(){
   //console.log(this.name,this.empoloyeeID);
   let customObj = new Custom();
   customObj.name = "something";
   customObj.employeeId = 12; 
   this.empList.push(customObj);
   this.name ="";
   this.empoloyeeID = 0; 
 }
}

또 다른 방법은 인터페이스가 설명서를 한 번 읽는 것입니다. - https://www.typescriptlang.org/docs/handbook/interfaces.html

또한 이 질문을 확인해 보십시오. 매우 흥미롭습니다 - TypeScript/Angular2에서 인터페이스와 모델을 사용할 때

당신의.empList개체 유형이지만 문자열을 푸시하려고 합니다.

사용해 보세요.

this.empList.push({this.name,this.empoloyeeID});

개체를 배열로 밀어넣습니다.사용해 보십시오.

export class FormComponent implements OnInit {
    name: string;
    empoloyeeID : number;
    empList: Array<{name: string, empoloyeeID: number}> = []; 
    constructor() {}
    ngOnInit() {}
    onEmpCreate(){
        console.log(this.name,this.empoloyeeID);
        this.empList.push({ name: this.name, empoloyeeID: this.empoloyeeID });
        this.name = "";
        this.empoloyeeID = 0;
    }
}

언급URL : https://stackoverflow.com/questions/47090080/add-items-in-array-angular-4

반응형