开发者问题收集

Angular 2:ViewChild 在父级上未定义

2017-06-22
3646

我遇到了以下错误:

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

错误在此行触发:

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

我看了很多帖子,但它们似乎都过时了,而且大多数帖子都说我必须使用 ngAfterViewInit 函数,我确实这样做了。 我有一个触发 updateTestId 的点击操作,我想将此 id 传递给我的子视图 ProductListComponent。 这是我的父组件:

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)

  }


}

这是我的子组件:

    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; }
*/

}

我使用子选择器如下:

<test-list></test-list>
<product-list #productList [test_id]="selected_test"></product-list>
2个回答

模板引用变量 名称 添加到模板中的 product-list

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

并在组件中引用它

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

编辑:

在这种情况下, Vivek Doshi 的回答是正确的,您不需要它,因为您正在通过 @Input 将数据传递给子项。但是 - 如果您想使用 ViewChild ,这是一个解决方案 :)

Fredrik Lundin Grande
2017-06-22

如果要将数据从父级传递给子级,可以直接传递

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

就是这样,仅此而已。

无需通过 @ViewChild 访问它


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

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

示例:

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

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

注意事项: 您需要在子组件上 实现 OnChanges

有关更多详细信息,请阅读此 文档

Vivek Doshi
2017-06-22