Angular 2将变量传递给HTML中的构造函数



我正在创建一个要在我的应用程序中重复使用的组件,下面的重要代码

.ts

export class DieInputComponent {
  constructor(private sides: Number, private dice: Number) { 
  }
}

.html

<input type="number" placeholder="{{dice}}d{{sides}}"/>

我在我的html模板中创建这些对象,例如so

<die-input></die-input>

我将如何输入html标签中的构造变量?对于我的一生,我找不到有关如何做的适当参考。

如果您需要在组件类中可用一些值

export class DieInputComponent{    
    @Input()sides:Number;
    @Input()dice:Number;
 }   
    <die-input [sides]='6' [dice]='1'></die-input>

您可以使用构造函数中的@Attribute关键字来获取属性值。这将为您提供您要搜索的属性的字符串值。对于您的示例,将是:

export class DieInputComponent {
  constructor(@Attribute('placeholder') theInput: string) {
    // theInput.length > 0?
    // theInput.split into dice/sides and parse into integers
  }
}

您可以在此处阅读有关@Attribute的更多信息:angular.io docs

最新更新