简体   繁体   中英

Angular Component Class Variable Set in one Function is Undefined in Another

I have a component with a viewChild() binding to a child component that I use to call a function in the child component. The function takes an argument of true or false and is meant to set a class variable in the child component to the argument's value. The class variable is then meant to be read in an if statement in another function in the child component.

So far, I have successfully called the child component function from the parent component, passed the boolean argument to it, set the class variable, and printed it to the console. I have verified that the class function is included in the 'this' of the component.

IN THE PARENT COMPONENT:

  if (res[0] === undefined) {
    this.typeAhead.badRequest(true);
  }

IN THE CHILD COMPONENT: The console log in the onSubmit() function only returns the value of _badRequestFlag set when the variable was declared, not the value assigned in badRequest().

private _badRequestFlag: boolean = false;

badRequest (res: boolean) {
  this._badPlaRequestFlag = res;
}

onSubmit (): void {
  console.log('BAD PLA REQUEST:, ', this);
    if (this._badRequestFlag === true) {
      alert('Does Not Exist');
      throw (new Error('Does Not Exist'));
}

When I try to use the class variable in the onSubmit() function, it's value is only the value that it was declared with, and not the value set in the badRequest() function. I'm assuming that I'm running into a scoping issue, but I cannot determine what and how to resolve it.

I would recommend setting the badRequestFlag using an input instead:

class ChildComponent {
  @Input() badRequestFlag: boolean;
}


@Component({
selector: 'app',
  template: `
    <child-component [badRequestFlag]="true"></child-component>
  `
})

You can bind this to a variable in the parent controller: [badRequestFlag]="requestFlag"

probably you should review the lifecycle-hooks , i try to understand you problem in stackblitz but i can't replay your decribed error. i hope help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM