当满足某些`*ngIf`条件时,如何从类装饰器调用某个方法?

ska*_*dev 6 typescript angular

*ngIf满足某些条件时,如何从类装饰器调用某个方法.我有一个完全像AngularJS问题的场景,其中使用ng-init()但ng-init不是Angular2的一部分

<div *ngIf="obj.someProperty" callSomeMethod() >
 <!--render inner parts-->
</div>
Run Code Online (Sandbox Code Playgroud)

dre*_*ore 2

这取决于callSomeMethod()正在执行的操作,但一种可能性是向元素添加指令*ngIf,并在该指令的钩子中执行该逻辑OnInit

<div *ngIf="obj.someProperty" some-method-directive>
   <!--render inner parts-->
</div>
Run Code Online (Sandbox Code Playgroud)

以及其他地方:

@Directive({
   selector='[some-method-directive]',
})
class SomeMethodDirective implements OnInit { // OnInit imported from angular2/core

   ngOnInit(){
      // insert your someMethod lofic
   }
}
Run Code Online (Sandbox Code Playgroud)

如果您需要在此方法中访问父组件,您可以通过指令中的构造函数注入来获取它:

constructor(@Host(ParentComponent) private parent: ParentComponent){ }
Run Code Online (Sandbox Code Playgroud)

然后您就可以通过 访问它this.parent

这是我能想到的与 ng1 方法最相似的方法,但就像我说的 - 根据someMethod()需要完成的任务,它可能不是一个可行的解决方案。如果没有,请评论/编辑您的问题以解释原因,这将使我更好地了解我们在这里所做的事情。