0

如何使用同一 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: ''
}

}
4

1 回答 1

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

于 2018-11-12T09:29:15.267 回答