Angular 2 : ViewChild is undefined on parent

2019-09-16 19:05发布

问题:

I have following error :

Error: Uncaught (in promise): TypeError: Cannot set property 'test_id' of undefined TypeError: Cannot set property 'test_id' of undefined

The errror is trigger on this line:

    console.log('after view init testList', this.productList.test_id);

I saw a lot of posts but all of them seems outdated and most of them are saying that I have to use a function ngAfterViewInit which I did. I have a clic action that triggers updateTestId and I want to pass this id to my child view ProductListComponent. Here is my parent component :

import { Component,ViewChild} from '@angular/core';

import {Test,TestData} from './testService';

import { LocalDataSource } from 'ng2-smart-table';
import {ProductListComponent} from '../../components/product/list/productList.component';



@Component({
  selector: 'test-list',
  templateUrl: './testList.html',
  styleUrls: ['./testList.scss']
})
export class TestListComponent{

  //tests: Test[];
  tests: any[];
  selected_test : number;


  @ViewChild(ProductListComponent)
  private productList: ProductListComponent;

  constructor(protected service: TestData){
    this.service.getData().then((data) => {
      this.tests = data.tests;
      this.source.load(data);
    });


  }

  settings = {
    editable : false,
    actions: {
      add:false,
      edit:false,
      delete:false
  },
  columns: {
      id: {
        title: 'ID',
        type: 'number'
      },
      nb_cartons: {
        title: 'Cartons',
        type: 'number'
      },
      nb_items: {
        title: 'Items',
        type: 'number'
      },
      nb_pallets: {
        title: 'Pallets',
        type: 'number'
      },
  };

  //source : Test[];
  source: LocalDataSource = new LocalDataSource();


  public updateTestId(value:any):void {

    this.selected_test = value.data.id;
    console.log('rowSelect', this.selected_test );
    //console.log(this.productList.test_id)

  }


}

And here is my child component :

    import { Component,Input,Output, OnChanges, SimpleChanges } from '@angular/core';

import { LocalDataSource } from 'ng2-smart-table';
import {Test} from '../../test/testService';

@Component({
  selector: 'product-list',
  templateUrl: './productList.html',
  styleUrls: ['./productList.scss']
})
export class ProductListComponent implements OnChanges{

  @Input() test_id : number = null;

  settings = {
    editable : false,
    actions: {
      add:false,
      edit:false,
      delete:false
    },
    columns: {
      id: {
        title: 'ID',
        type: 'number'
      },
      sku: {
        title: 'SKU',
        type: 'string'
      },
      reference: {
        title: 'Reference',
        type: 'string'
      },
      size: {
        title: 'Size',
        type: 'string'
      },
    },
    edit: {
      editButtonContent: '<i class="ion-edit"></i>',
      saveButtonContent: '<i class="ion-checkmark"></i>',
      cancelButtonContent: '<i class="ion-close"></i>',
    }
  };

  source: LocalDataSource = new LocalDataSource();


  constructor() {

  }

  ngOnChanges(changes: SimpleChanges) {
    console.log(changes['test_id'],changes['test_id'].currentValue);
    console.log('change in child',changes.test_id);
  }

  /*
  @Input()
  set _test_id(id: number) {
    this._test_id = id;
  }

  get test_id(): number { return this._test_id; }
*/

}

i use the child selector like this :

<test-list></test-list>
<product-list #productList [test_id]="selected_test"></product-list>

回答1:

If you want to pass data from parent to child you can directly pass

<product-list [test_id]="selected_test"></product-list>

That's it , nothing more.

There is no need to access it via @ViewChild


To detect the changed value over the time from product-list component

ngOnChanges(changes: SimpleChanges) {
    console.log(changes['test_id'].currentValue);
}

Example :

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnChanges {
  @Input()
  prop: number;

  ngOnChanges(changes: SimpleChanges) {
    // changes.prop contains the old and the new value...
  }
}

Things to note : You need to implements OnChanges on child component.

For more detail please read this doc



回答2:

Add a template reference variable name to the product-list in the template

<product-list #productList [test_id]="selected_test"></product-list>

And reference it by that in the component

@ViewChild('productList')
private productList: ProductListComponent;

EDIT:

In this case Vivek Doshi is correct in his answer that you don't need it since you are passing data to the child via @Input. But still - if you want to use ViewChild, this is a solution :)