如何使用同一ts文件中的材质对话框从另一个组件清除表单数据?

时间:2018-11-12 09:20:40

标签: angular

如何使用同一ts文件中的材料对话框从另一个组件清除表单数据?

这是我的.ts文件

@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: ''
}

}

1 个答案:

答案 0 :(得分:1)

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
  }

}

顺便说一句,只有在app-enter-user包含clear-confirmation-dialog时才能起作用

例如:

 enter-user.component.html:

....
<clear-confirmation-dialog></clear-confirmation-dialog>
....

您最好将@Optional()@Host()装饰器添加到 enter_user_component

  

有关forwardRef的更多信息:

     

https://angular.io/api/core/forwardRef