[英]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. 我有一个带有viewChild()的组件,该组件绑定到子组件,该子组件用于在子组件中调用函数。 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. 该函数接受true或false的参数,并且旨在将子组件中的类变量设置为参数的值。 The class variable is then meant to be read in an if statement in another function in the child component. 然后,将在子组件中另一个函数的if语句中读取class变量。
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. 到目前为止,我已经成功地从父组件调用了子组件函数,将boolean参数传递给了它,设置了类变量,并将其打印到控制台。 I have verified that the class function is included in the 'this' of the component. 我已经验证了类函数包含在组件的“ this”中。
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(). 在儿童组件中:onSubmit()函数中的控制台日志仅返回声明该变量时设置的_badRequestFlag的值,而不返回在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. 当我尝试在onSubmit()函数中使用类变量时,它的值仅是使用其声明的值,而不是badRequest()函数中设置的值。 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: 我建议改用输入设置badRequestFlag:
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"
您可以将其绑定到父控制器中的变量: [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. 也许您应该检查一下生命周期挂钩 ,我试图了解您在stackblitz中遇到的问题,但是我无法重播您描述的错误。 i hope help you 希望对你有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.