如何解决为什么我的客户指令不起作用?
我的主要目的是使用客户指令根据用户登录或注销显示不同的页面
<!-- 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,以说明其工作原理。将鼠标悬停在两个元素上时,您可以看到控制台
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。