且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过角度2中的指令标签访问值

更新时间:2023-01-15 20:25:52

您的代码看起来正确.您可以以正确的方式访问指令值,但是您似乎希望可以在构造函数中对其进行设置.您需要了解的是,您的组件已构建(也称为构造函数),并且 then 已初始化(包括检索@Input属性).

Your code looks correct. You access your directive value the right way, but you seem to expect it to be set in the constructor. What you need to understand is, your component is built (aka constructor) and then is initialized (including retrieving @Input properties).

因此,在执行ngOnInit()之前获得undefined是预期的行为.之后,您的hero变量将被设置为输入值.

Therefore it is the expected behaviour to get undefined before ngOnInit() got executed. After that, your hero variable will be set to the input value.

我可能会误解您对保持不变的值的疑问,但是只要您不更新您的imageId变量(以及输入内容),就没有理由更改您的hero.

I might missunderstand your questionning about the value remaining the same, but as long as you don't update your imageId variable (and therefore the input), there is no reason your hero should be changed.