简体   繁体   English

在角度4中将@Input的值用于没有onInit的其他变量

[英]Use value of @Input to other variable without onInit in angular 4

I want to use @Input value to initialize other variable in angular 4 我想使用@Input值在angular 4中初始化其他变量

export class test {
  @Input() id: string;

  condition: boolean = (this.id == 'myid') //Getting this.id as undefined
}

Your @Input is first available at ngOnInit . 您的@Input首先可在ngOnInit So you can't access it before ngOnInit call. 因此,您不能在ngOnInit调用之前访问它。

You can use id variable directly like id instead of this.id inside a class itself. 您可以在类本身内部直接使用id变量(例如id代替this.id You have to access variable using this only when variable appeared inside function . 仅当变量出现在function内部时,才需要使用this变量。 But eventually this wouldn't help you, since id value will always be undefined . 但这最终无济于事,因为id值始终是undefined

Ideally you should use this value inside ngOnInit hook which gets fired when component gets initialized and you will see the value passed from the consumer component. 理想情况下,您应该在ngOnInit挂钩中使用此值, ngOnInit挂钩在组件初始化时会触发,并且您会看到从使用者组件传递的值。

export class test {
  @Input() id: string;
  condition: boolean;

  ngOnInit(){
     this.condition = (this.id == 'myid')
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM