[英]Cannot read “target” property when passing value from child to parent component
In my project student
is child component of the parent app
component.在我的项目中,
student
是父app
组件的子组件。
The student
component template
has an input element as below: student
组件template
有一个输入元素,如下所示:
<input type='text' #inputbox (keyup)='onkeyUp(inputbox.value)'>
The student
component has defined onkeyUp
event handler as below: student
组件定义onkeyUp
事件处理程序,如下所示:
@Component({
outputs: ['childevent']
...
childevent = new EventEmitter();
onkeyUp(value: any) {
this.childevent.emit(value);
}
The parent app
component looks as below:父
app
组件如下所示:
...
<label>Value of Child Component: </label> {{Cdata.target.value}}
<app-student (childevent)='Cdata=$event'></app-student>
Here, {{Cdata.target.value}}
is throwing an error:在这里,
{{Cdata.target.value}}
抛出错误:
ERROR TypeError: Cannot read property 'target' of undefined
As per my understanding, $event
has the entire childevent
payload which is passed to the Cdata
event handler.据我了解,
$event
具有传递给Cdata
事件处理程序的整个childevent
有效负载。 And, event.target.value
returns the current contents of childevent
并且,
event.target.value
返回childevent
的当前内容
Please let me know if I have correct understanding.如果我有正确的理解,请告诉我。 I am referring to angular docs
我指的是angular 文档
I have tried to use optional chaining
我尝试使用
optional chaining
<label>Value of Child Component: </label> {{Cdata?.target.value}}
But still getting an error但是还是报错
ERROR TypeError: Cannot read property 'value' of undefined
The problem is that in your app template
, Cdata
does not yet exist when the template is rendered for the first time.问题是在您的应用程序
template
中,第一次呈现模板时, Cdata
还不存在。 You can solve this by changing the code as follows:您可以通过如下更改代码来解决此问题:
<label>Value of Child Component: </label> {{ Cdata ? Cdata.target.value : 'missing' }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.