Arū*_*kas 3 javascript angular2-directives angular
Angular2中的指令没有"范围",而组件则没有.但就我而言,我需要Directive来创建一个范围.查看我的App组件 - 它有一个HTML模板,并且该foo指令可以出现的任何元素上都有ANYWHERE .这应该从服务中获取一些日期并将其分配给元素.
在Angular1中,它很容易......指令可以有自己的范围.但在Angular 2中,我找不到任何(甚至是肮脏的)方法来实现这一点.
它看起来像一个简单的任务,不是吗?
@Directive({
selector: '[foo]'
})
class FooDirective {
@Input()
public id:string;
public bar;
constructor() {
this.bar = 'This is the "bar" I actually need. It is taken from DB let's say..' + this.id;
}
}
@Component({
selector: 'app',
template: `
<div foo id="2">
This is random content 1: {{bar}}
</div>
<div foo id="2">
This is random content 2: {{bar}}
</div>
`,
directives: [FooDirective]
})
class App {
bar:string = 'This should be ignored, I need "bar" to be set from directive!';
}
bootstrap(App);
Run Code Online (Sandbox Code Playgroud)
你可以尝试使用一个引用应用指令的局部变量:
@Component({
selector: 'app'
template: `
<div foo id="2" #dir1="foo">
This is random content 1: {{dir1.bar}}
</div>
<div foo id="2" #dir2="foo">
This is random content 2: {{dir2.bar}}
</div>
`,
directives: [FooDirective]
})
class App {
bar:string = 'This should be ignored, I need "bar" to be set from directive!';
}
Run Code Online (Sandbox Code Playgroud)
在您的情况下bar,使用当前组件的属性来评估App.
编辑(关注@ yurzui的评论)
您需要exportAs在指令中添加属性:
@Directive({
selector: '[foo]',
exportAs: 'foo'
})
class FooDirective {
(...)
}
Run Code Online (Sandbox Code Playgroud)