angular - 传递给指令的值有时未定义
问题描述
在 Angular 组件上,我有以下内容:
export class PostAboutComponent implements OnInit {
postId: number;
constructor(private route: ActivatedRoute, private router: Router, private postService: PostService) { }
ngOnInit() {
this.route.paramMap.subscribe(parameters => {
this.postId = parameters.has('postId') ? +parameters.get('postId') : undefined;
})
}
}
在组件的 HTML 上,我有:
<p *authorize="'EditPost'; id postId">
<button (click)="editPost()">Edit post</button>
</p>
授权指令如下:
export class AuthorizeDirective implements OnInit {
private notifier: Subscription;
requirement: Requirement;
id: number;
@Input() set authorize(requirement: string) {
this.requirement = Requirement[requirement];
}
@Input() set authorizeId(id: number) {
this.id = id;
}
constructor(private element: ElementRef, private template: TemplateRef<any>, private container: ViewContainerRef, private renderer: Renderer2, private authorizationService: AuthorizationService) { }
ngOnInit() {
console.log("id: " + this.id);
this.authorizationService.authorize(this.requirement, this.id).pipe(
distinctUntilChanged()
).subscribe(x => {
x ? this.container.createEmbeddedView(this.template) : this.container.clear();
});
}
}
id
发生的情况是,有时undefined
在 Authorize 指令中:
console.log("id: " + this.id);
其他时候不是......如果我刷新页面永远不会不确定。
我在这里想念什么?
解决方案
您需要按如下方式更改 HTML 才能使绑定生效,
为了将值绑定到结构指令标识符,请使用identifier_name: valueToBind
<p *authorize="'EditPost'; id: postId">
<button (click)="editPost()">Edit post</button>
</p>
推荐阅读
- c# - EF创建的数据库查询问题
- python - Python 类中的自我
- c++ - 具有 const 引用的 C++ Setter 成员函数在运行时导致“读取访问冲突”异常
- php - .htaccess 在数字海洋服务器中不起作用
- python - Google KickStart 错误答案
- javascript - 如何处理带有惰性和路由组件的 vue 组合 API?
- vert.x - 即使工作线程可用,Vertx Http Webclient 请求也会挂起
- tensorflow - 为什么在 Tensorflow 教程中将 sqrt(dim) 与 Transformer 的编码输入相乘?
- javascript - 拥有“ ?${new Date().getTime()} ”如何更新 JS 中的图像
- swiftui - ForEach 不能使用分支