我今天遇到了类似的需求,但我没有找到很多资源,所以我尝试了 C# 泛型的方式,它成功了。所以我在下面发布了一个小例子的发现。
因此,为了实现这一点,我们需要像下面这样将泛型类型持有者添加到子组件中,以便我们可以从父组件传递类型:
import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent<TType> {
@Input() genericType?: TType;
@Output() selected: EventEmitter<TType> = new EventEmitter<TType>();
onClick(): void {
if (this.genericType) {
this.selected.emit(this.genericType);
}
}
}
然后从父级,我们需要传递所需的对象类型。在这里,我传递了示例的数字和字符串。
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
genericTypeNumber: number= 2022;
genericTypeString: string= "Hello World!!";
constructor() { }
ngOnInit(): void {
}
onSelectedNumber(numberType: number){
console.log(numberType);
}
onSelectedString(stringType: string){
console.log(stringType);
}
}
在父 HTML 中,将属性正常分配给子组件:
<app-child [genericType]="genericTypeNumber" (selected)="onSelectedNumber($event)"></app-child>
<app-child [genericType]="genericTypeString" (selected)="onSelectedString($event)"></app-child>
这也将确保类型安全。
如果您需要在现有接口中使用泛型类型,则可以执行以下操作。
export interface IGenericModel<TCustomType> {
id: number;
customValue: TCustomType;
}
子组件会是这样的:
import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';
import { IGenericModel } from './genericModel';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent<TType> {
@Input() genericType?: IGenericModel<TType>;
@Output() selected: EventEmitter<IGenericModel<TType>> = new EventEmitter<IGenericModel<TType>>();
onClick(): void {
if (this.genericType) {
this.selected.emit(this.genericType);
}
}
}