问题描述
我的主要目的是使用客户指令根据用户登录或注销显示不同的页面
<!-- Show this for logged out users -->
<ul *appShowAuthed="false"
class="nav navbar-nav pull-xs-right">
<li class="nav-
<li class="nav-item">
<a class="nav-link" routerLink="/register" routerLinkActive="active">
Sign up
</a>
</li>
</ul>
<!-- Show this for logged out users -->
<ul *appShowAuthed="true"
class="nav navbar-nav pull-xs-right">
<li class="nav-item">
<a
class="nav-link"
routerLink="/"
routerLinkActive="active"
[routerLinkActiveOptions]="{ exact: true }">
</a>
</li>
</ul>
我的客户指令
import { UserService } from './user.service';
import { Directive,TemplateRef,ViewContainerRef,OnInit,Input } from '@angular/core';
@Directive({
selector: '[appShowAuthed]'
})
export class ShowAuthedDirective implements OnInit {
constructor(
private templateRef: TemplateRef<any>,private userService: UserService,private viewContainerRef: ViewContainerRef
) {}
condition: boolean;
ngOnInit() {
this.userService.isAuthenciated.subscribe(
(isAuthenticated) => {
if (isAuthenticated && this.condition || !isAuthenticated && !this.condition) {
this.viewContainerRef.createEmbeddedView(this.templateRef);
} else {
this.viewContainerRef.clear();
}
}
);
}
@Input() set appShowAuthed(condition: boolean) {
this.condition = condition;
}
}
我将其导入到标题模块中
import { ShowAuthedDirective } from './../show-authed.directive';
import { NgModule } from '@angular/core';
@NgModule({
declarations: [
HeaderComponent,ShowAuthedDirective
],imports: [],providers: []
})
export class headerModule {}
但是当我启动它时,它在google chrome中显示如下:core.js:7813无法绑定到'appShowAuthed',因为它不是'ul'的已知属性
解决方法
您应该在CommonModule
上的导入数组下放置headerModule
import { ShowAuthedDirective } from './../show-authed.directive';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
@NgModule({
declarations: [
HeaderComponent,ShowAuthedDirective
],imports: [ CommonModule ],providers: []
})
export class headerModule {}
更新
HTML上有一个*
前缀。应该将其删除
从*appShowAuthed
删除*标记。因为您使用了自定义指令。
我做了一个简单的Stackblitz,以说明其工作原理。将鼠标悬停在两个元素上时,您可以看到控制台