Bill Gardner
Bill Gardner

Reputation: 196

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.

Upvotes: 0

Views: 640

Answers (2)

elcordova
elcordova

Reputation: 136

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

Upvotes: 0

Anton Bks
Anton Bks

Reputation: 492

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"

Upvotes: 2

Related Questions