也许这是正常行为,进行测试,this.myColor这是未定义的,但为什么呢?我的代码错误的错误:
<h1 myDR [myColor]="red" > Test </h1>
Run Code Online (Sandbox Code Playgroud)
import {Component, Directive, Input, ElementRef} from 'angular2/core';
@Directive({
selector: '[myDR]',
host:{
'(mouseenter)' : ' mouseEnter()'
}
})
export class MyDi {
@Input () myColor: string;
constructor(private el:ElementRef) {
}
mouseEnter(){
this.el.nativeElement.style.backgroundColor = this.myColor;
console.log(this.myColor);
}
}
@Component({
selector: 'my-app',
template: `<h1>Hello World Angular2</h1>
<h1 myDR [myColor]="red" > Test </h1>
`,
directives: [MyDi]
})
export class App {
constructor(){
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将鼠标移到"测试"上并查看控制台
Eri*_*nez 47
你必须用简单的引号将输入绑定括起来,就像这样
[myColor]="'red'"
Run Code Online (Sandbox Code Playgroud)
这会将red字符串绑定到myColor.如果删除简单引号,它将查找名为red不存在的类属性,因此返回undefined
你可以像我上面提到的那样做,或者你可以创建一个名为的类属性red.在这种情况下,它将绑定到类属性.
@Component({
template: `<h1 myDR [myColor]="red" > Test </h1>`
})
export class App {
red: string = 'red';
}
Run Code Online (Sandbox Code Playgroud)
编辑
我忘了提到nativeElement不鼓励访问DOM .你应该使用Renderer,@ HotBinding或host属性@Component(最后两个是等价的).所以你还有三个选择
host财产@Directive({
host:{
'(mouseenter)' : ' mouseEnter()',
'[style.background-color]' : 'myColor'
}
})
mouseEnter(){
this.myColor = 'blue';
}
Run Code Online (Sandbox Code Playgroud)
@HostBinding(这种情况下会立即设置颜色)@HostBinding('style.background-color') get color {
return this.myColor;
}
mouseEnter(){
this.myColor = 'blue';
}
Run Code Online (Sandbox Code Playgroud)
Renderer(使用此代替nativeElement.style = 'value')constructor(public renderer: Renderer, public element: ElementRef) {}
mouseEnter(){
this.renderer.setElementStyle(this.element.nativeElement, 'background-color', this.myColor);
}
Run Code Online (Sandbox Code Playgroud)
一种更简单的绑定静态文本的方法是
<h1 myDR myColor="red" > Test </h1>
Run Code Online (Sandbox Code Playgroud)
请参阅"一次性字符串初始化"下的Angular2文档.
| 归档时间: |
|
| 查看次数: |
15414 次 |
| 最近记录: |