Lan*_*ara 1 typescript angular
我想创建一个指令,我可以使用模板变量,这样我就可以访问全局变量,类似于$rootScopeAngular.JS,而不必在我需要变量的每个组件中注入服务.
例如:
@Directive({
selector: '[app]',
exportAs: 'app'
})
export class AppDirective {
isLoggedIn: boolean = false;
constructor() {
// Do some stuff to set 'this.ready'...
}
}
Run Code Online (Sandbox Code Playgroud)
我希望能够在我的模板中使用上面的代码,如下所示:
<div #app>
<div *ngIf="app.isLoggedIn">...</div>
</div>
Run Code Online (Sandbox Code Playgroud)
这样的事情可能吗?
如果使用指令而不是ngIf,那么只需将服务注入到指令中,在组件中使用时,它也很好,DRY和最小化标记.
就像是
@Directive({
selector: '[showIfLoggedIn]'
})
export class ShowIfLoggedInDirective implements OnInit {
constructor(
private templateRef: TemplateRef<any>,
private viewContainerRef: ViewContainerRef
) { }
ngOnInit() {
var isLoggedIn = false;//TODO use service here and inject into constructor.
if( isLoggedIn ) {
this.viewContainerRef.createEmbeddedView(this.templateRef);
} else {
this.viewContainerRef.clear();
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后用
<h2 *showIfLoggedIn> I am logged in </h2>
Run Code Online (Sandbox Code Playgroud)
并切换课程
@Directive({
selector : '[applyClassIfLoggedIn]'
})
export class ApplyClassIfLoggedIn implements OnInit {
@Input('applyClassIfLoggedIn') className;
constructor(
private ele: ElementRef,
private renderer: Renderer2
) { }
ngOnInit() {
var isLoggedIn = true;//TODO use service here.
if( isLoggedIn ) {
this.renderer.addClass(this.ele.nativeElement, this.className);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后
<h2 applyClassIfLoggedIn='logged-in'>Red if logged in </h2>
Run Code Online (Sandbox Code Playgroud)