[英]How to "pass down" Typescript type to Angular component @Input decorator
I'm somewhat new to Angular, and still am working to understand the more complex aspects of Typescript, so forgive me if this question is poorly worded, and/or the answer is obvious.我对 Angular 有点陌生,并且仍在努力了解 Typescript 更复杂的方面,所以如果这个问题措辞不当和/或答案很明显,请原谅我。
I have a simple Angular component to display a dropdown menu.我有一个简单的 Angular 组件来显示下拉菜单。 My initial pass had this as the inputs/output:
我最初的传球将其作为输入/输出:
@Input() options: OptionType[] = [];
@Input() selectedOption: OptionType = { name: '', value: '' };
@Output() onChangeEvent = new EventEmitter<OptionType>();
...where OptionType
is: ...其中
OptionType
是:
type OptionType = {
name: string;
value: string;
}
The problem is that callers of this component usually have limited possible values for both name
and value
.问题是该组件的调用者通常对
name
和value
的可能值有限。 For example, I might an option set that is:例如,我可能有一个选项集:
[
{name: 'No', value: 'no'},
{name: 'Yes', value: 'yes'}
]
In the type declared by the parent, I restrict the possible types to what you see above, and that leads to a collision between, for example, 'no' | 'yes'
在父级声明的类型中,我将可能的类型限制为您在上面看到的类型,这会导致例如
'no' | 'yes'
之间的冲突。 'no' | 'yes'
and string
. 'no' | 'yes'
和string
。
What I'd like to be able to do is to say that the main OptionType
of this component should be inherited from the caller.我想做的就是说这个组件的主要
OptionType
应该从调用者那里继承。 I know this kind of thing is generally done with Typescript generics, but I don't know how to do what I want in this context, or even if such a thing is possible/smart.我知道这种事情通常是用 Typescript generics 完成的,但我不知道如何在这种情况下做我想做的事情,或者即使这样的事情是可能的/聪明的。
Thanks in advance for any guidance!提前感谢您的任何指导!
Here's my updated TS file for the component.这是我更新的组件 TS 文件。 There's not much to it, so I figured there's no harm in posting the whole thing.
没什么大不了的,所以我认为发布整个内容并没有什么坏处。
The selectedOption
line seems a little weird to me, but I think I understand it. selectedOption
行对我来说似乎有点奇怪,但我想我明白了。 My first inclination was to set it to T
, but there's no guarantee that the default value I set in the code below will be a member of T
, so it makes sense that it has to be OptionType
.我的第一个倾向是将其设置为
T
,但不能保证我在下面的代码中设置的默认值将是T
的成员,因此它必须是OptionType
是有道理的。
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
type OptionType = {
name: string;
value: string;
};
@Component({
selector: 'app-dropdown',
templateUrl: './dropdown.component.html',
styleUrls: ['./dropdown.component.scss'],
})
export class DropdownComponent<T extends OptionType> implements OnInit {
@Input() options: T[] = [];
@Input() selectedOption: OptionType = { name: '', value: '' };
@Output()
onChangeEvent = new EventEmitter<T>();
constructor() {}
ngOnInit(): void {}
onChange(option: any) {
this.onChangeEvent.emit(option);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.