代码之家  ›  专栏  ›  技术社区  ›  Harish

如何在angular 5中不使用*ngFor将数据从父组件发送到子组件

  •  2
  • Harish  · 技术社区  · 7 年前

    实际上,我使用*ngFor来重复一个选择器,并且我还将一些数据发送给子组件。请查看下面的代码:

    <app-piegraph *ngFor="let studentData of studentData" [studentData]="studentData"></app-piegraph>
    

    父组件:

    studentData = {first: "harish",second: "santhu"}
    

    子组件:

    export class PiegraphComponent implements OnInit{
      @Input('studentData') testObj;
    constructor(){
    console.log(this.testObj); //Getting undefined error message here
    }
    }
    

    我的studentData中只有一个对象,因此我不想重复数据,我只想将studentData对象发送到我的子组件,而不使用*ngFor

    这可能吗???

    1 回复  |  直到 7 年前
        1
  •  2
  •   AT82    7 年前

    自从你 studentData 是一个数组,您可以确定它只有一个可以执行的对象:

    <app-piegraph [studentData]="studentData[0]"></app-piegraph>
    

    这里我们需要记住在父组件中初始化数组,这样我们就不会得到 undefined 阵列错误。

    此外,您正在尝试控制台日志 @Input 值,此时 @输入 值尚不可用。可以通过将控制台日志移动到 OnInit :

    export class PiegraphComponent implements OnInit{
      @Input('studentData') testObj;
    
      constructor(){ }
    
      ngOnInit() { 
        console.log(this.testObj);
      }
    }