【问题标题】:Value passed to directive is sometimes undefined传递给指令的值有时未定义
【发布时间】:2020-01-09 21:01:30
【问题描述】:

在 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 在 Authorize 指令中是 undefined

console.log("id: " + this.id);

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

我在这里错过了什么?

【问题讨论】:

标签: angular angular8


【解决方案1】:

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

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

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

【讨论】:

  • 你确定this.postId 在控制器中有价值吗?
  • 是的,它在组件中具有价值......我试图弄清楚问题是否出在其他地方。
  • 您可以通过在@Input set 方法中添加控制台日志来检查@Input 是否被调用。
猜你喜欢
  • 2015-12-25
  • 1970-01-01
  • 1970-01-01
  • 2016-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-14
相关资源
最近更新 更多