3

I am creating a component to be reused throughout my app, the important code below

.ts

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

.html

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

I am creating these objects in my html templates like so

<die-input></die-input>

How would I go about inputting the constructor variables in a html tag? For the life of me I can't find an appropriate reference on how to do it.

4

2 回答 2

6

If you need some value to be available inside your component class then simply use @Input variable and pass the value as attribute of your component

export class DieInputComponent{    
    @Input()sides:Number;
    @Input()dice:Number;
 }   
    <die-input [sides]='6' [dice]='1'></die-input>
于 2016-06-20T05:10:53.677 回答
5

You can get the attribute values by using the @Attribute keyword in the constructor. This will give you the string value of the attribute you are searching for. For your example it would be:

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

You can read more about @Attribute here: angular.io docs

于 2016-06-20T04:49:54.297 回答