簡體   English   中英

在Angular中將多個數據從父組件傳遞到子組件時遇到錯誤

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

我試圖將兩個變量從父組件發送到子組件。 為此,我已經在一個對象中初始化了這兩個數據,您可以在下面看到

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

我已將子選擇器放置到父組件視圖.html文件中,在其中使用@input名稱myInput將其綁定到對象名稱。

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

但是在子組件中,當我使用對象值時..我無法訪問父對象中已定義對象的鍵值

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

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

appcomponent

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

應用程序組件html

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

表單測試組件

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

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

以上對我來說很好用。

注意:myInput:string我將其更改為myInput:any,盡管在運行時不會引起任何錯誤。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM