问题描述
我的表单输入字段是否为必填项,取决于API数据集。但是当它强制执行时,我需要禁用按钮,直到用户输入一些值为止。我是角度反应式的绝对初学者。需要一些专家帮助才能做到这一点。
------------ HTML ----------------------
<div class="a">
<at-card *ngIf="selectedId$|async" class="b">
<at-detail [selectedDetail]="selectedDetailModel$|async">
</at-detail>
<div [formGroup]="DetailForm" class="grid grid-columns-2">
<br />
<mat-form-field>
<mat-label>Comment</mat-label>
<input matInput formControlName="comment" [type]="'text'" [required]="commentRequerd">
</mat-form-field>
</div>
</at-card>
<at-sticky-footer>
<button *ngIf="selectedId$|async" (click)="onSubmit()">submit</button>
</at-sticky-footer>
</div>
------------------ component.ts ------------------
commentRequerd: boolean;
DetailForm = new FormGroup({ comment: new FormControl(),rate: new FormControl() });
ngOnInit(): void {
inputCommentIsMandotory:boolean = <take API data about enter comment needed or not>
//accroding to that input comment filed mark as requred->
//is it requred need to check user input data to comment field ->
//if it avalable button is enable,else it disable
if(inputCommentIsMandotory){
this.commentRequerd = true;
//when user enter data button enable,if not disable(input field empty)
}else{
//alwasy button enable (input comment or not)
this.commentRequerd = false;
}
}
------------------最新更新(即使注释不是强制性的,也始终禁用按钮--------------- ---------------------
我像下面一样更改了代码。
isCommentMandatory(Reviews: ReviewModel[]): void {
if (Reviews.length > 0) {
console.log("called ...1 ");
this.isCommentRequired = false;
this.DetailForm = this.fb.group({
comment: [''],rate: ['']
});
} else {
console.log("called ...2 ");
this.isCommentRequired = true;
this.DetailForm = this.fb.group({
comment: ['',Validators.required],rate: ['']
});
}
}
并这样称呼它,
ngOnInit(): void {
this.DetailModel$.pipe().subscribe((opd => {
this.detail = opd as Detail;
const date = this.detail?.time;
const planDate = date !== undefined ? date : new Date();
//according date select reviews data
this.store.select(selectAllReviewsDetailsModel(planDate)).
subscribe(res => this.Reviews = res);
//need to call after change Details
this.isCommentMandatory(this.Reviews);
}));
}
在其绑定的html模板中,
<at-sticky-footer>
<button *ngIf="selectedId$|async" [disabled]="!(DetailModel.valid && (DetailModel.dirty))" (click)="submit()">submit</button>
</at-sticky-footer>
但是现在,两种情况都需要输入一些内容来启用按钮。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)