Canberk Dogmus
Canberk Dogmus

Reputation: 55

Cannot read property 'onchange' of undefined error when calling function

I have popular error about Angular 2. When I'm calling function from another component I face this error.

"Cannot read property 'onChange' of undefined at CD019.onChangeParent"

My codes below:

  @ViewChild('testComponent') testComponent: CD020;

onChangeParent() {
    this.testComponent.onChange;

}

and child component is

   @Output() childChanged = new EventEmitter<string>();
    onChange(value: string, test: string) {
        this.childChanged.emit(value);
        this.Test(test);
    }

Thanks for your help already.

Upvotes: 0

Views: 1217

Answers (2)

John
John

Reputation: 11399

You need to make sure @ViewChild(ChildType) testComponent: ChildType uses the same type E.g.your child component:

@Component({
  selector: 'app-my-child',
  templateUrl: './my-child.component.html',
  styleUrls: ['./my-child.component.css']
})
export class CD020 implements OnInit {
    ngOnInit() {
    }
    @Output() childChanged = new EventEmitter<string>();
    onChange(value: string, test: string) {
        this.childChanged.emit(value);
    }
}

your parent html:

<app-my-child></app-my-child> <!-- uses the template selector name -->

your parent code:

//note the name inside the viewChild and the type of testComponent
@ViewChild(CD020) testComponent: CD020;

onChangeParent() {
    // must pass two arguments.
    this.testComponent.onChange("someValue","someTest");

}

Upvotes: 0

Hampus
Hampus

Reputation: 2799

According to the documentation you shall use the component type as the identifier for the ViewChild decorator. https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html

@ViewChild(CD020) testComponent: CD020;

Upvotes: 1

Related Questions