admin管理员组文章数量:1356304
I'm working on a form and have a property that will be one of several types. I created this custom type for the property.
export type IngredientDataGroupType =
FormGroup< FlourProfileGroup > |
FormGroup< SaltProfileGroup > |
FormGroup< SugarProfileGroup > |
FormGroup< GrainProfileGroup > |
FormGroup< NutProfileGroup > |
FormGroup< SpeciesPrimative > |
FormGroup< DairyProfileGroup > |
FormGroup< ProduceProfileGroup > |
FormGroup< OilProfileGroup > |
FormGroup< HerbProfileGroup > |
FormGroup< ExtractProfileGroup > |
FormGroup< SweetenerProfileGroup >;
I apply this type to an @Input()
in my component and started to set up an @switch
statement in my template file to toggle the appropriate component. I also have another @Input()
for passing in a value to determine which @case
to return. Seeing that all my Profile
components are strictly typed none of the will accept type IngredientDataGroupType
which means I have to return the data as the type the component accepts. Instead of bloating my component by handling it like this.
export class MyComponent {
@Input() Control! : IngredientDataGroupType;
@Input() ProfileType! : IngredientProfileType;
flourProfile() : FormGroup< FlourProfileGroup > {
return this.Control as FormGroup< FlourProfileGroup >;
}
saltProfile() : FormGroup< SaltProfile > {
return this.Control as FormGroup< SaltProfile >;
}
// etc. etc. for each profile
}
So instead I figured I'd do this
export class MyComponent {
@Input() Control! : IngredientDataGroupType;
@Input() ProfileType! : IngredientProfileType;
getControl< GroupType extends Record< string, AbstractControl< any, any > > >() : FormGroup< GroupType > {
return this.Control as FormGroup< GroupType >;
}
}
and use it like this in my template
<section class="mainContainer"[formGroup]="Control">
@if( Control !== undefined ) {
@switch ( ProfileType ) {
@case ( 'flour' ) {
<lib-flour-profile
ngDefaultControl
[Control]="getControlGroup<FlourProfileGroup>()"
/>
}
}
}
</section>
I'm getting a couple of errors, one in regards to the <lib-flour-profile />
component's [Control]
input saying it can't accept type boolean, then one with the getControlGroup()
method saying it's possibly undefined.
Why is the getControlGroup()
method returning type boolean
? This is just something I was trying to see if it would work, can we even infer types like this in the template? How can I go about achieving this type of functionality?
本文标签:
版权声明:本文标题:angular - Properly rendering components depending on the type of the object in a prop with multiple potential types - Stack Over 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744049247a2582113.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论