How to access the values through directive tag in angular 2

你离开我真会死。 提交于 2019-12-25 16:57:25

问题


My firsthtml,

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

My first.component.ts,

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

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
  }
 }

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.


回答1:


https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#oninit

Use ngOnInit() for two main reasons:

  1. To perform complex initializations shortly after construction.

  2. To set up the component after Angular sets the input properties.




回答2:


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).

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.

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.



来源:https://stackoverflow.com/questions/43202840/how-to-access-the-values-through-directive-tag-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!