0

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.

2
  • I think the functionality you're looking for in ViewChild is backwards. If you were to do the opposite and try and set the variable in the parent component, this would work. When communicating from parent to child, it's best practice to use the @Input operator instead and pass the variable through the parent dom using the [] syntax. Commented Aug 19, 2019 at 19:29
  • A question like this really needs an minimal reproducible example. You are asking too much of others to attempt to envision, test, and run this without one. You might want to check out StackBlitz.... Commented Aug 19, 2019 at 20:10

2 Answers 2

2

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"

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.