问题
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:
To perform complex initializations shortly after construction.
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