简体   繁体   English

Angular2指令属性绑定

[英]Angular2 directive property binding

I have a directive that either shows or hides a sidebar on click. 我有一个指令,可以在单击时显示或隐藏侧栏。 I want to create an option to show the sidebar or hide the sidebar on i. 我想创建一个选项来显示侧边栏或隐藏i上的侧边栏。

My component.html: 我的component.html:

<button class="sidebar-minimizer" type="button" appSidebarMinimizer [minimizeSide] = "open" appBrandMinimizer></button>

I created a property [minimizeSide] = "'open'" 我创建了一个属性[minimizeSide] = "'open'"

My component.ts 我的component.ts

export class AppSidebarMinimizerComponent {
  open = "open";

}

My directive: 我的指令:

@Directive({
  selector: '[appSidebarMinimizer]'
})
export class SidebarMinimizeDirective {
  @Input() minimizeSide:string;
  constructor() {
    if (this.minimizeSide == "open"){
      document.querySelector('body').classList.toggle('brand-minimized');
    }
  }

  @HostListener('click', ['$event'])
  toggleOpen($event: any) {
    $event.preventDefault();
    document.querySelector('body').classList.toggle('sidebar-minimized');
  }
}

The click function works fine but it doesn't work while init. 单击功能可以正常工作,但在初始化时不起作用。 What am I missing? 我想念什么?

Here the reason to your problem are listed below: 下面列出了导致您的问题的原因:

  • @Input field will be updated when first change detection got executed @Input字段将在执行首次更改检测时更新
  • Directive, as also Component, will be constructed first and then runs life-hook ( OnChanges => OnInit and so on)of itself. 指令以及组件都将首先构造,然后运行其自身的生命周期( OnChanges => OnInit等)。

So you won't get value bound to @Input unless OnChange life hook of your directive got executed. 因此,除非执行了指令的OnChange生命挂钩,否则您将不会获得绑定到@Input值。 You can move the initialization code block to directive's OnInit life hook. 您可以将初始化代码块移至指令的OnInit生命周期挂钩。

constructor() { }

ngOnInit() {
  if (this.minimizeSide == "open"){
    document.querySelector('body').classList.toggle('brand-minimized');
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM