首页 > 解决方案 > 将 @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() {
  }
}

标签: angular

解决方案


目前没有办法实现您的目标,即使您将buttonType类型从字符串更改为整数,它仍然会毫不犹豫地接受字符串值。我认为这部分是因为绑定是 Angular 自己的功能,而不是 Typescript,所以 Typescript 无法识别您正在传递其他类型。


推荐阅读