angular - 将 @Input 限制为 Angular 中的预定义值列表
问题描述
我试图限制@Input
预定义值的列表,但仍然可以从父级接受任何值。即使Enum
它也接受一切,而不是枚举值。
子组件
import { Component, OnInit, Input} from '@angular/core';
@Component({
selector: 'app-button',
template: `<div>
<button [type]="buttonType">
{{buttonText}}
</button>
</div>`
})
export class ButtonComponent implements OnInit {
@Input() buttonType: 'reset' | 'submit' | 'button' = 'button';
@Input() buttonText: string;
ngOnInit() {
}
}
父组件
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
template: `<app-button buttonText="Action1" buttonType="accepts anything"></app-button>`
})
export class AppComponent implements OnInit {
title = 'Test Component';
ngOnInit() {
}
}
解决方案
目前没有办法实现您的目标,即使您将buttonType
类型从字符串更改为整数,它仍然会毫不犹豫地接受字符串值。我认为这部分是因为绑定是 Angular 自己的功能,而不是 Typescript,所以 Typescript 无法识别您正在传递其他类型。
推荐阅读
- c# - 使用 .NET Core Web API 3.1 进行基于 JWT 角色的授权时出现 403 错误
- ios - Swift 用特殊关键字标记枚举元素
- python - 如何组合两个数据框并自然地对混合字母数字类型的列进行排序?
- html - 引导 div 错位
- javascript - 希望将 Tabulator 和 Wavesurfer.js 波形图片组合成单独的行
- python - UnicodeDecodeError:“utf-8”编解码器无法解码位置 0 中的字节 0xb0:无效的起始字节
- spring - spring data jpa和jpa实现
- c# - Wpf mahapps按条件折叠数据网格行不起作用
- tcp - tcp[tcpflags] & tcp-syn == tcp-syn, tcp[tcpflags] == tcp-syn, tcp[13] == tcp-syn, tcp[13] & tcp-syn != 0
- java - 让 Java 方法调用处理程序执行时传入的可变参数