Issue
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.
I have a simple Angular component to display a dropdown menu. 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:
type OptionType = {
name: string;
value: string;
}
The problem is that callers of this component usually have limited possible values for both name
and 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'
and 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. 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.
Thanks in advance for any guidance!
Solution
Here's my updated TS file for the component. 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. 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
.
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);
}
}
Answered By - hairbo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.