是否可以将类型传递给可以“更新”的Angular组件?

时间:2020-06-06 23:13:11

标签: angular class newable

我正在开发通用下拉组件。如果用户输入的值不在列表中,则我想在itemSelected事件中返回相同类型的新对象 。我需要保留方法以及属性-因此,仅创建通用对象是行不通的。即使列表为空,这也需要工作,因此无法执行类似Object.create(this.list [0]);的操作。

到目前为止,我的解决方法是只传递一个引用对象,我可以将其与Object.create一起使用,但这似乎很la脚。

以下代码片段显示了我正在尝试执行的操作。有没有办法做到这一点,或者有更好的办法做到我想要的?谢谢-乔恩

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-generic-new',
  templateUrl: './generic-new.component.html',
  styleUrls: ['./generic-new.component.scss']
})
export class GenericNewComponent implements OnInit {
  ngOnInit(): void {}

  @Input() type:any 

  createNewType():any {
    // this is what I'm trying to do - but doesn't work
    return new this.type();
  }
}

1 个答案:

答案 0 :(得分:1)

使用泛型

class container<T> {
    id: T;
    key: T;
    displayValue: T;
    type : T;        
}
//allows you to control the type, here we are allowing any, but could be person, address etc.
let myContainer = new container<any>();
myContainer.id = 0;
myContainer.key = "UserEnteredKey";
myContainer.displayValue = "UserEnteredDisplayValue;
myContiner.type //allow access to anything or a specific class type.

不使用泛型。

class container{
 id:number;
 key:number;
 displayValue:string;
 type:any;
}
let myContainer = new contaier();
myContainer.number = 10;
myContainer.key = "UserEnteredKey";
myContainer.displayValue = "User Entered Display Value";
myContainer.type = {key:myContainer.key, display: myContainer.displayValue, doSomething: function(){//do something here.}}

请注意,上面的任何值都可以计算,而不是静态的,例如,通常计算ID。

 @Input() type:container

  createNewType():any {
    // this is what I'm trying to do - but doesn't work
    return
     let myContainer = new container<any>();
     myContainer.id = this.getNextID();
     myContainer.key = "UserEnteredKey";
     myContainer.displayValue = "UserEnteredDisplayValue;
     myContiner.type //allow access to anything or a specific class type.
}

您的表单将需要通过绑定到此Cass模型来公开用户需要更改的所有属性。