简体   繁体   English

在angular2中的指令之前加载组件

[英]loading component before directive in angular2

I made small component in angular2 application that I am useas a directive, to enter small view in different pars of application. 我在angular2应用程序中创建了一个小组件,我用它作为指令,在不同的应用程序中输入小视图。 I only define options in the component where I am using this directive . 我只在我使用此指令的组件中定义选项。 This directive always expects to have options, and in my case it takes time until it gets the data from server and only then 'someOptions' will be defined. 该指令总是希望有选项,在我的情况下,它需要时间才能从服务器获取数据,然后才会定义'someOptions'。 But this 'example' component expects it right away, how can I postpone it? 但是这个“示例”组件立即期待它,我该如何推迟呢? Do you know how can I keep using this as a directive but tell angular to only activate it once the options are defined in component that is using this directive? 你知道我怎么能继续使用它作为一个指令但是告诉angular只有在使用这个指令的组件中定义了选项后才激活它?

// the directive Im planning to use in differnt views
@Component({
  selector: 'expml-comp'
})

export class Example1 {
@Input() options: any;
  constructor() {}
  ngOninit(){
    //puting data from options to directive
  }
}

//and the component where I want to use this directive:
@Component({
  template: '<expml-comp [options] = 'definedData'></expml-comp>',
})
 export class Example2 {
  constructor() { }
  private definedData:any;
 //here I need to define the options but before the data comes from server      //the Example1 dir is already activated 
//and it didnt find definedData so it breaks
 ngOnInit(){
//this.definedData=...
 }

}

You can use ngOnChanges() . 您可以使用ngOnChanges() This method is called when a value bound to an input was changed. 绑定到输入的值发生更改时,将调用此方法。

export class Example1 {
  @Input() options: any;
  constructor() {}
  ngOnChanges(changes){
    if(this.options != null) {
      // options are set
    }
  }
}

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

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