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

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

问题描述

我的firsthtml,

My firsthtml,

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

我的first.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上对其进行操作时,它会显示该值,但是当我在其外部进行相同的操作时,它会显示undefined.在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.

推荐答案

您的代码看起来正确.您可以以正确的方式访问指令值,但是您似乎希望可以在构造函数中对其进行设置.您需要了解的是,您的组件已构建(也称为构造函数),并且 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.

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

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