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 {
(...)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。