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

Cri*_*ann 2 angular2-components angular

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

.ts

export class DieInputComponent {
  constructor(private sides: Number, private dice: Number) { 
  }
}
Run Code Online (Sandbox Code Playgroud)

.html

<input type="number" placeholder="{{dice}}d{{sides}}"/>
Run Code Online (Sandbox Code Playgroud)

我正在像这样在我的 html 模板中创建这些对象

<die-input></die-input>
Run Code Online (Sandbox Code Playgroud)

我将如何在 html 标签中输入构造函数变量?对于我的生活,我找不到关于如何做的合适参考。

Rav*_*mar 6

如果您需要一些值在您的组件类中可用,那么只需使用 @Input 变量并将该值作为组件的属性传递

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


Sjo*_*erd 5

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

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

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