【发布时间】:2019-10-30 19:02:03
【问题描述】:
是否可以使用@Output 进行回调?
我有一个FormComponent,它检查有效性,并在提交时禁用提交按钮。现在我想在提交完成后重新启用提交按钮。
@Component({
template: `
<form [formGroup]="form" (ngSubmit)="onSubmit()">
...
</form>
`
})
class FormComponent {
form: FormGroup = ...;
isSubmitting = false;
@Output()
submitted = new EventEmitter<MyData>()
onSubmit() {
if(this.form.invalid || this.isSubmitting) {
return;
}
this.isSubmitting = true;
this.submitted.emit(this.form.value);
// Here I'd like to listen for the result of the parent component
// something like this...
// this.submitted.emit(...).subscribe(res => this.isSubmitting = false);
}
}
@Component({
template: `
<my-form (submitted)="onSubmitted($event)"></my-form>
`
})
class ParentComponent {
constructor(private service: MyService) { }
onSubmitted(event: MyData) {
this.service.doSomething(event).pipe(
tap(res => console.log("service res", res)
);
// basically I'd like to `return` this `Observable`,
// so the `FormComponent` can listen for the completion
}
}
我知道,我可以在 FormComponent 中使用 @Input() 并执行以下操作:
@Input()
set submitted(val: boolean) {
this.isSubmitted = val;
}
但我想知道是否有更简单/更好的解决方案,因为isSubmitted 应该是FormComponent 的内部属性,它应该由组件本身而不是其父级管理。
【问题讨论】:
-
我认为在服务中这样做更优雅。你可以在任何你想要的地方注入服务。我会在服务中使用
isSubmitted$: Subject<boolean>。 -
你的意思是某种
FormService?那么它必须由ParentComponent提供(因为同一个表单可以在同一个屏幕上多次显示)。然后FormComponent注入它并观察isSubmitted$流。是的,这也可能有效。但我希望有更简单的东西...... -
更短的版本是在父级中使用
@ViewChild(FormComponent) form,然后使用form.isSubmitting = false。有效地完成相同的工作。
标签: angular callback rxjs eventemitter