Angular属性装饰器添加到组件的生命周期钩子?

时间:2017-11-14 22:34:17

标签: angular

以下代码允许我向我的组件添加@Test(),但是我需要向ngOnInit钩子添加一个命令,它当前替换组件中的钩子。

function Test(value:any) {

  return function(target: any, propertyKey: string | symbol) {

    target.ngOnInit = () => {
      console.log("This replaces the component's hook")
    }

  }
}    

我如何添加?

1 个答案:

答案 0 :(得分:2)

装饰器实际上只是函数,方法装饰器将使用它正在装饰的方法的值来调用,并且将使用要装饰的类调用类装饰器。

decorator下面只是将类记录到控制台:

function Console(target) {
  console.log('Our decorated class', target);
}

目标实际上是我们装饰的类,这意味着我们现在可以用装饰器装饰任何类,并在控制台中看到它输出:

@Console
class ExampleClass {
  constructor() {
    console.log('Yo!');
  }
}

link to detail decorator获取此信息。谷歌有很多可用的例子。

希望它有所帮助。

相关问题