如何通过angular 2中的指令标签访问值 [英] How to access the values through directive tag in angular 2

查看:19
本文介绍了如何通过angular 2中的指令标签访问值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的第一个html,

   <modal [hero]="imageId"></modal>-->

我的第一个.component.ts,

My first.component.ts,

 export class CommonComponent  {
     photodata:any;
     imageId:any = '2';
 }

我的model.component.ts,

My model.component.ts,

 @Component({
   selector: 'modal',
   templateUrl: './app/modal/modal.component.html',
   providers: [HeaderClass]
 })

export class ModalComponent implements OnInit  {
    @Input() hero: string;
    console.log(hero)--->Undefined
  constructor(){
   console.log(this.hero)---->undefined
 }
  ngOnInit(){
    console.log(this.hero)---->2
  }
 }

在这里,当我在 ngOnInit 上对其进行控制台时,它会显示该值,但是当我在其外部执行相同操作时,它会显示未定义.我正在从 firstcomponent 访问此模态组件,但 hero 值未更改,它保持相同的值,因为它是在 ngOninit() 中?.任何人都可以帮助我.谢谢.

Here when I console it on ngOnInit it shows the value but when I do the same out side of it it says undefined.I am accessing this modal component from firstcomponent but the hero value is unchanged it remains with same value since it is in ngOninit()?.Can any one please help me.Thanks.

推荐答案

您的代码看起来正确.您以正确的方式访问指令值,但您似乎希望在构造函数中设置它.您需要了解的是,您的组件已构建(也称为构造函数),然后然后 被初始化(包括检索 @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.

这篇关于如何通过angular 2中的指令标签访问值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆