首页 > 解决方案 > 传递给指令的值有时未定义

问题描述

在 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);

其他时候不是......如果我刷新页面永远不会不确定。

我在这里想念什么?

标签: angularangular8

解决方案


您需要按如下方式更改 HTML 才能使绑定生效,

为了将值绑定到结构指令标识符,请使用identifier_name: valueToBind

<p *authorize="'EditPost'; id: postId">
  <button (click)="editPost()">Edit post</button>
</p>

推荐阅读