Angular 2:从装饰器访问注入的依赖项
发布时间:2020-12-17 06:48:09 所属栏目:安全 来源:网络整理
导读:我正在制作一个可重复使用的Angular2组件,我希望用户能够指定一个模板字符串或templateUrl,然后该组件将通过属性或通过某种服务方法设置该组件. 在Angular 1中,这很简单,我们可以这样做: // somewhere else in appmyService.setTemplateUrl('path/to/templa
|
我正在制作一个可重复使用的Angular2组件,我希望用户能够指定一个模板字符串或templateUrl,然后该组件将通过属性或通过某种服务方法设置该组件.
在Angular 1中,这很简单,我们可以这样做: // somewhere else in app
myService.setTemplateUrl('path/to/template.html');
// directive definition
function myDirective(myService) {
return {
template: function(element,attrs) {
return attrs.templateUrl || myService.getTemplateUrl();
}
// ...
};
}
如何在Angular2中实现这一目标? @Component({
selector: 'my-component',template: '...' // cannot see `mySerivce` from here,nor access the element attributes
})
export class MyComponent {
constructor(private myService: MyService) {}
}
虽然我的问题特别涉及如何实现动态模板,但更广泛的问题是是否可以从各种装饰器访问注入的依赖项实例. 解决方法
所以我终于想出了一种方法来使用自定义模板做我想做的事情.
我认为实际问题的答案必须是否定的,注射器在装饰器中不可用.这是我对Angular 2组件生命周期的理解. 对于那些感兴趣的人,以下是我提出的用于实现用户定义的自定义模板的内容: 给定一个指令SimpleTimer,我们可以提供这样的自定义模板: <!-- app.ts template -->
<div *simpleTimer="#timer=timerApi">
<div class="time">{{ timer.getTime() }}</div>
<div class="controls">
<button (click)="timer.toggle()">Toggle</button>
<button (click)="timer.reset()">Reset</button>
</div>
</div>
然后使用如下的TemplateRef和ViewContainerRef注射剂: // SimpleTimer.ts
constructor(private templateRef: TemplateRef,private viewContainer: ViewContainerRef,private cdr: ChangeDetectorRef) {}
ngOnInit() {
// we need to detach the change detector initially,to prevent a
// "changed after checked" error.
this.cdr.detach();
}
ngAfterViewInit() {
let view = this.viewContainer.createEmbeddedView(this.templateRef);
let api = {
toggle: () => this.toggle(),reset: () => this.reset(),getTime: () => this.getTime()
}
view.setLocal('timerApi',api);
setTimeout(() => this.cdr.reattach());
}
有关如何以及为何如此有效的演练,请访问please see this blog post I wrote up on the topic. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
