gpt4 book ai didi

angular - 共享组件的验证

转载 作者:行者123 更新时间:2023-12-04 09:31:17 25 4
gpt4 key购买 nike

我正在尝试为文件上传制作一个共享组件,以便在需要时重用它。如果我将文件上传代码放在表单的相同 html 中,则验证有效。如果我将其作为单独的组件进行验证,则验证不起作用。
注意:我想在某些组件中对文件进行验证,而不想在其他组件中进行验证
这里正在工作 stackblitz我尝试过的代码

<form [formGroup]="formLocation" (ngSubmit)="onSubmitFarmLocation()">
<div class="form-row">
<div class="form-group col-sm-4">
<label>Property Identification Number</label>
<input class="form-control" type="text" formControlName="propertyIdentificationNumber"
[class.invalid]="!formLocation.controls['propertyIdentificationNumber'].valid && formLocation.controls['propertyIdentificationNumber'].touched " >
<div
*ngIf="!formLocation.controls['propertyIdentificationNumber'].valid && (formLocation.controls['propertyIdentificationNumber'].touched || isSubmitted)">
<div class="invalid-feedback" style="display: block;">Please enter property identification
Number
</div>
</div>
</div>
<hr>
<app-sharedfile></app-sharedfile>
<div class="form-row">
<div class=" ml-auto pb-3">
<button type="submit" class="btn btn-primary" >Submit</button>
</div>
</div>
</div>
</form>

最佳答案

您可以借助辅助服务和一个简单的 Subject 来实现这一点,而无需对当前代码进行太多更改。
我有一个服务 FileService,它有一个主题,当用户单击“保存”按钮时,您可以在主组件中使用它。

export class FileService {
checkFileUploadSubject = new Subject<boolean>();

setCheckFileUploadValidity() {
this.checkFileUploadSubject.next(true);
}

checkFileUploadValidity(): Observable<boolean> {
return this.checkFileUploadSubject.asObservable();
}
}
在您的主组件中,您可以通过在此 FileService Subject 实例上调用 next 方法来通知共享组件。
app.component.ts
onSubmitFarmLocation() {
this.isSubmitted = true;
this.isShowErrors = true;
this.fileService.setCheckFileUploadValidity();
if (this.formLocation.invalid) {
return;
}

console.log(this.formLocation.value, this.formLocation.errors);
}
然后,您可以在共享组件中监听此 Subject 发出的事件,并通过将 FormContrls 标记为已触摸来检查错误。
ngOnInit() {
this.fileService.checkFileUploadValidity().subscribe(value => {
debugger;
this.formLocation.markAllAsTouched();
});
}
请在此处找到工作代码: https://stackblitz.com/edit/angularfi-leupload-xfpdfr

关于angular - 共享组件的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62832305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com