来自文档 https://angular.io/docs/ts/latest/guide/attribute-directives.html
与组件一样,您可以添加尽可能多的指令属性绑定
您需要将它们串在模板中。
添加输入属性HighlightDirective
called defaultColor
:
@Input() defaultColor: string;
Markup
<p [myHighlight]="color" defaultColor="violet">
Highlight me too!
</p>
Angular知道defaultColor
绑定属于HighlightDirective
因为你公开了@Input
装饰师。
无论哪种方式,@Input
装饰器告诉 Angular 这个属性是
公共且可供父组件绑定。没有@Input
, Angular 拒绝绑定该属性。
对于你的例子
有很多参数
将属性添加到Directive
与 一起上课@Input()
装饰者
@Directive({
selector: '[selectable]'
})
export class SelectableDirective{
private el: HTMLElement;
@Input('selectable') option:any;
@Input('first') f;
@Input('second') s;
...
}
并在模板中将绑定属性传递给您的li
element
<li *ngFor = 'let opt of currentQuestion.options'
[selectable] = 'opt'
[first]='YourParameterHere'
[second]='YourParameterHere'
(selectedOption) = 'onOptionSelection($event)'>
{{opt.option}}
</li>
这里关于li
元素我们有一个带有名称的指令selectable
。在里面selectable
我们有两个@Input()
's, f
有名字first
and s
有名字second
。我们已将这两个应用到li
带有名称的属性[first]
and [second]
。我们的指令将在其上找到这些属性li
元素,为他设置@Input()
装饰师。所以selectable
, [first]
and [second]
将受到每个指令的约束li
,它具有这些名称的属性。
具有单一参数
@Directive({
selector: '[selectable]'
})
export class SelectableDirective{
private el: HTMLElement;
@Input('selectable') option:any;
@Input('params') params;
...
}
Markup
<li *ngFor = 'let opt of currentQuestion.options'
[selectable] = 'opt'
[params]='{firstParam: 1, seconParam: 2, thirdParam: 3}'
(selectedOption) = 'onOptionSelection($event)'>
{{opt.option}}
</li>