[英]@Input() Decorator and directives Angular-2
I am new to angular2, I have 2 questions :- 我是angular2的新手,我有两个问题: -
1. I want to know why this is correct 1.我想知道为什么这是正确的
<p myHighlight [color1]='color' defaultColor="violet">Highlight me!</p>
and these are not 而这些都不是
<p myHighlight color1='color' defaultColor="violet">Highlight me!</p>
<p myHighlight [color1]='color' [defaultColor]="violet">Highlight me!</p>
Why i have to put only 1 property in brackets and the other without brackets. 为什么我只需要在括号中放置一个属性而另一个没有括号。
2. How can i use @Input() directive without aliasing in my code. 2.如何在代码中使用@Input()指令而不使用别名。 does it work for multiple properties ?
它适用于多个属性? Here is my directive code :
这是我的指令代码:
import { Input, Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[myHighlight]'
})
export class myDir {
constructor(private el: ElementRef) {
}
@Input('color1') color: string;//for ts code 'color' for html code 'myHighlight' i.e template component
@Input('defaultColor') defaultColor: string;
@HostListener('mouseenter') onMouseEnter() {
this.highlight(this.color || this.defaultColor);
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(null);
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
my html code :- 我的HTML代码: -
<div>
<input type="radio" name="clr" (click)="color='lightgreen'">Green
<input type="radio" name="clr" (click)="color='yellow'">Yellow
<input type="radio" name="clr" (click)="color='cyan'">Cyan
</div>
<p myHighlight [color1]='color' [defaultColor]='violet'>Highlight me!</p>
First One 第一
<p myHighlight color1='color' defaultColor="violet">Highlight me!</p>
color1 and default color are not attributes of paragraph tag so it will not work. color1和默认颜色不是段落标记的属性,因此不起作用。
Second 第二
<p myHighlight [color1]='color' [defaultColor]="violet">Highlight me!</p>
Your directive sets the color1 property to your paragraph tag and there is no violet variable in the component. 您的指令将color1属性设置为您的段落标记,并且组件中没有紫色变量。
Everything inside [ ]
are property bindings and those properties are represented using @Input()
decorator. [ ]
内的所有内容都是属性绑定,这些属性使用@Input()
装饰器表示。
Note: When you are using a component variable to bind property it should be in [ ]. 注意: 当您使用组件变量绑定属性时,它应该在[]中。 If you are using direct value then you need not enclose in square brackets
如果您使用的是直接值,则无需将其括在方括号中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.