my form input field required or not decide according to the API data set. But when it mandatory, I need to disable button, until user input some value. I am an absolute beginner for reactive form in angular. need some expert help to do this.
------------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;
}
}
------------------latest update (button always disable , even if a comment is not mandatory ------------------------------------
I changed the code like bellow.
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: ['']
});
}
}
and called it like this,
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);
}));
}
In the html template it bind has below,
<at-sticky-footer>
<button *ngIf="selectedId$|async" [disabled]="!(DetailModel.valid && (DetailModel.dirty))" (click)="submit()">submit</button>
</at-sticky-footer>
but now , both situation need to type something to enable button .