When it comes to deciding whether my form input field is required or not, I rely on the API data set. If the input is mandatory, I want to disable the button until the user inputs some value. As an absolute beginner in reactive form in angular, I could really use some expert guidance on how to achieve 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]="commentRequired">
</mat-form-field>
</div>
</at-card>
<at-sticky-footer>
<button *ngIf="selectedId$|async" (click)="onSubmit()">submit</button>
</at-sticky-footer>
</div>
------------------component.ts------------------
commentRequired: boolean;
DetailForm = new FormGroup({ comment: new FormControl(), rate: new FormControl() });
ngOnInit(): void {
inputCommentIsMandatory:boolean = <retrieve API data about whether entering a comment is required or not>
//Based on the API data, mark the comment field as required
//Check if user input is needed for the comment field
//If it is required, check if there is user input in the comment field ->
//Enable the button if there is, otherwise disable it
if(inputCommentIsMandatory){
this.commentRequired = true;
//Enable the button when user enters data, disable it if the input field is empty
}else{
//Button always enabled (whether comment is entered or not)
this.commentRequired = false;
}
}
------------------latest update (button always disable, even if comment is not mandatory ------------------------------------
I have updated the code as follows.
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();
//Select reviews data based on the date
this.store.select(selectAllReviewsDetailsModel(planDate)).
subscribe(res => this.Reviews = res);
//Need to call after changing Details
this.isCommentMandatory(this.Reviews);
}));
}
In the HTML template, it is bound as below,
<at-sticky-footer>
<button *ngIf="selectedId$|async" [disabled]="!(DetailModel.valid && (DetailModel.dirty))" (click)="submit()">submit</button>
</at-sticky-footer>
However, now in both scenarios, something needs to be typed in to enable the button.