Angular 5中this.value返回undefined的问题求助
undefined Issue in Your Angular 5 Component Hey there, let's break down the problems in your code and get that this.value undefined issue sorted out!
1. Syntax Error in Parent Component Property Initialization
First up, your parent component has incorrect syntax for initializing the sendMaj and sendMin properties. In TypeScript, you use the = operator to assign values, while : is reserved for type annotations. Your current code will throw a syntax error, which is likely contributing to unexpected undefined values.
Corrected Parent Component Code:
import { Component } from '@angular/core' @Component({ selector: "parent-onchange", template: ` <br> from parent component <button value="minor" (click)="updateMin()">Minor</button> <button value="major" (click)="updateMaj()">Major</button> <child-onchange [major]="sendMaj" [minor]="sendMin"></child-onchange> ` }) export class ParentCompOnChange { // Correct property initialization with optional type annotation sendMaj: number = 1; sendMin: number = 23; // Implement missing update methods to modify values on button click updateMin() { this.sendMin++; // Example: increment minor version } updateMaj() { this.sendMaj++; // Example: increment major version } }
2. Ensure Child Component Properly Receives & Uses Inputs
The this.value undefined error is almost certainly coming from your child-onchange component. You need to make sure the child correctly declares input properties with @Input(), and references them properly (not a vague this.value) in your logic.
Example Child Component Code:
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; @Component({ selector: 'child-onchange', template: ` <p>Major Version: {{ major }}</p> <p>Minor Version: {{ minor }}</p> ` }) export class ChildCompOnChange implements OnChanges { // Declare input properties matching the parent's bound values @Input() major: number; @Input() minor: number; ngOnChanges(changes: SimpleChanges) { // Access updated values using the actual input property names if (changes.major) { console.log('Major version updated to:', this.major); } if (changes.minor) { console.log('Minor version updated to:', this.minor); } } }
Key Fixes Explained:
- Parent Component: Fixed property initialization syntax and added the missing
updateMin()/updateMaj()methods so clicking buttons actually updates values passed to the child. - Child Component: Used
@Input()to properly receivemajorandminorvalues from the parent. If you were usingthis.valuebefore, you probably meant to referencethis.majororthis.minorinstead.
If you still see undefined, double-check:
- The child component's input property names exactly match the ones bound in the parent's template (
[major]and[minor]). - The child component is added to your Angular module's
declarationsarray.
内容的提问来源于stack exchange,提问作者Punit

