javascript – 带范围的Angular2指令
作者:互联网
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);
解决方法:
你可以尝试使用一个引用应用指令的局部变量:
@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!';
}
在您的情况下,使用当前组件(App one)的属性评估栏.
编辑(关注@ yurzui的评论)
您需要在指令中添加exportAs属性:
@Directive({
selector: '[foo]',
exportAs: 'foo'
})
class FooDirective {
(...)
}
标签:javascript,angular,angular2-directives 来源: https://codeday.me/bug/20190829/1758306.html