Search code examples
angularangular-decorator

Getting error in Passing multiple data from parent to child component in Angular


I am trying to send two variable from parent component to the child component. For that, I have initialized both data in an object you can see below

export class AppComponent {
  title = 'app';
  myObj = {
    FirstInputString : 'Hello I am coming from Parent',
    SecondInputString :  'I am second value coming from parent'
  };

I have placed the child selector to the parent component view .html file, where I used @input name myInput to bind it to the object name.

<app-form-test [myInput]='myObj' (myOutput)="getData($event)"></app-form-test>

But In the child component when I am using the object value .. I am not able to access the key value of the defined object in the parent object

export class FormTestComponent implements OnInit {
  @Input() myInput: string;

  ngOnInit() {
    console.log(this.myInput.FirstInputString);
    console.log(this.myInput.SecondInputString);
  }
}

Solution

  • appcomponent

    export class AppComponent {
      title = 'app';
      myObj = {
        FirstInputString : 'Hello I am coming from Parent',
        SecondInputString :  'I am second value coming from parent'
      };
    

    app component html

    <app-form-test [myInput]="myObj" (myOutput)="getData($event)"></app-form-test>
    

    form test component

    export class FormTestComponent implements OnInit {
      @Input() myInput: any;
    
      ngOnInit() {
        console.log(this.myInput.FirstInputString);
        console.log(this.myInput.SecondInputString);
      }
    }
    

    above works perfectly fine for me.

    Note: myInput: string I changed it to myInput: any, though which doesn't cause any error while running.

    Please find stackblitz https://stackblitz.com/edit/angular-8skzfj?file=src%2Fapp%2Fheader%2Fheader.component.ts