Angular 如何使用同一ts文件中的“材质”对话框从另一个组件清除表单数据?
如何使用同一ts文件中的“材质”对话框从另一个组件清除表单数据 这是我的.ts文件Angular 如何使用同一ts文件中的“材质”对话框从另一个组件清除表单数据?,angular,Angular,如何使用同一ts文件中的“材质”对话框从另一个组件清除表单数据 这是我的.ts文件 @Component({ selector: 'clear-confirmation-dialog', templateUrl: './clear-confirmation-dialog.html' }) export class ClearConfimationDialog { clearForm(){ /** FUNCTION TO CLEAR FORM DATA **/ } }
@Component({
selector: 'clear-confirmation-dialog',
templateUrl: './clear-confirmation-dialog.html'
})
export class ClearConfimationDialog {
clearForm(){
/** FUNCTION TO CLEAR FORM DATA **/
}
}
@Component({
selector: 'app-enter-user',
templateUrl: './enter-user.component.html',
styleUrls: ['./enter-user.component.scss']
})
export class EnterUserComponent implements OnInit {
/** THIS IS THE FORM DATA **/
user = {
name: '',
address: ''
}
}
将
EnterUserComponent
注入ClearConfimationDialog
@Component({
selector: 'clear-confirmation-dialog',
templateUrl: './clear-confirmation-dialog.html'
})
export class ClearConfimationDialog {
enter_user_component:EnterUserComponent;
clearForm(){
/** FUNCTION TO CLEAR FORM DATA **/
this.enter_user_component.clearForm()
}
constructor(@Inject(forwardRef(() => EnterUserComponent)) enter_user_component:EnterUserComponent){
this.enter_user_component = enter_user_component
}
}
顺便说一句,只有当应用程序进入用户
时,才可以使用清除确认对话框
例如:
enter-user.component.html:
....
<clear-confirmation-dialog></clear-confirmation-dialog>
....
enter-user.component.html:
....
....
您最好将@Optional()
和@Host()
装饰器添加到输入用户组件
有关forwardRef的更多信息:
共享调用此选择器的
html
,并共享EnterUserComponent
的html,我只想调用clearForm()
从ClearConfimationDialog
到EnterUserComponent
中的user
数组,这些组件是否具有父子关系?这两个组件位于同一个ts文件中。只需在ClearConfimationDialog
上使用继承即可解决问题,该继承读取为导出类ClearConfimationDialog扩展了EnterUserComponent
,因此您可能会获得用户数据-在函数中重置它我尝试注入EnterUserComponent
,然后我得到了此错误未捕获错误:无法解析ClearConfimationDialog的所有参数这两个组件位于相同的文件中。ts
我已更新答案是,您可以使用forwardRef来避免这个问题看起来您的第一个答案是正确的,我只是将对话框组件放在EnterUserComponent之后,它解决了允许引用尚未定义的引用的问题。还可以更改同一文件中两个零部件的位置:)