我编写了一个带有@Output EventEmitter
属性的指令:
@Directive({
selector: '[ifValid]'
})
export class SubmitValidationDirective {
@Output('ifValid') valid = new EventEmitter<void>();
constructor(
private formRef: NgForm
) {}
@HostListener('click')
handleClick() {
this.emitIfValid();
}
private emitIfValid() {
if (this.formRef.valid) {
this.valid.emit();
}
}
}
所以,我是这样使用的:
<button (ifValid)="save()">
那么,在我的组件中:
private save() {
this.service.push(this.user, this.toCreate)
.pipe(
take(1)
)
.subscribe();
}
手动订阅让我觉得很烦人。
我希望在ifValid
提升时,添加这个运算符-类似于switchMap(() => this.service.push(...))
。
我想知道是否可以通过超文本标记语言订阅ifValid
。我的意思是,我可以在我的组件中订阅ifValid
吗?
我希望我已经解释得很好。
发布于 2019-06-03 17:34:51
您可以在组件中使用@ViewChield(SubmitValidationDirective) component;
,然后可以使用
this.component.valid.subscribe(() => {this.service.push(this.user, this.toCreate)
.pipe(
take(1)
)
.subscribe();
});
但是你必须输入unsubscribe()
,比如你的ngOnDestroy
发布于 2019-06-03 17:37:46
是的,您可以这样做,因此我们需要创建一个服务,并在该服务上声明@Output
SharedService
@Output('ifValid') valid = new EventEmitter<void>();
componentOne
ngOnInit() {
this.sharedService.valid.subscribe(resp => {
this.save()
});
}
private save() {
this.service.push(this.user, this.toCreate)
.pipe(
take(1)
)
.subscribe();
}
指令或组件
import { SharedService } from 'Sharedservice';
@Directive({
selector: '[ifValid]'
})
export class SubmitValidationDirective {
constructor(private sharedService: SharedService) { }
@Output('ifValid') valid = new EventEmitter<void>();
constructor(
private formRef: NgForm
) {}
@HostListener('click')
handleClick() {
this.emitIfValid();
}
private emitIfValid() {
if (this.formRef.valid) {
this.sharedService.valid.emit(null);
}
}
}
https://stackoverflow.com/questions/56424480
复制相似问题