简体   繁体   中英

Angular to send the get property value from parent to child component

I have parent component that will send the value to child component from get property. Value that is sent to child component is shown in the same parent HTML page but it is not reachable to child component.

Tried using new method, tried all the lifecycle to fetch the value from the parent component nothing was helpful, also i tried using Viewchild to some extent but neither that helped me to get the value.

parent.component.ts

get name(): string {
 return this.service.name.toLocaleLowerCase(); // returns the name Eg: Tom
}

parent.component.html

<child [name]="name"></child>
name::: {{name}} <!--display name as Tom in the parent HTML-->

child.component.ts

@Input() name: string;
 constructor() {
  console.log(name); // logs unknown
}

The above console.log displays as unknown

i tried to console.log inside ngOnInit method - it displays unknown i tried using ngOnChanges(changes: SimpleChanges) - but for some reason the value is not getting printed first time but second time it gets printed which is not useful. Can anyone please suggest?

i need to fetch the input value inside contructor method.

I think your child component is loaded before the service's name variable value is initialized. check service's value is already initialized and after that load your child component.

try with

<child [name]="name" *ngIf="this.service.name"></child> 

We have to access the @Input value using this keyword

@Input() name: string;
 constructor() {
  console.log(this.name); //value passed from parent to the child
}
  1. You have to use a life cycle hook in which inputs are set. Such as ngOnChanges , or ngOnInit

  2. To access a member (class) variable in javascript/typescript you have to qualify it with this .

  @Input() name: string;

  ngOnInit() {
    console.log(this.name); // logs unknown
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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