How to clear input field after submitting data in angular? - html

I have one mat-select dropdown and one input field. When the button is clicked it submits data. After data is submitted I want to clear the input field but I don't want to clear the mat-select dropdown. How can I do that?
chat.component.html
<div>
<mat-form-field>
<mat-select placeholder="Select User" [(ngModel)]="userObject.userid"
name="userid" required>
<mat-option *ngFor="let userObj of userObj [value]="userObj.userid">
{{userObj.username}}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Type Message" [(ngModel)]="userObject.chatmessage">
</mat-form-field>
<button mat-raised-button color="primary" (click)="sendMessage()">
SEND MESSAGE</button>
</div>

Since you're two-way data binding to userObject.chatmessage, just setting it to an empty string in your component will do the trick.
In your ChatComponent TypeScript class, just do this:
sendMessage() {
// After Sending Message
userObject.chatmessage = '';
}

I think you should use Reactive forms and call reset()-method on the form.
You can also manually reset the form fields as suggested above by SiddAjmera.

I think the Reactive form is the best way to do it, https://angular.io/guide/reactive-forms use this link to do it
reset the input field by assigning the empty string is not the way to do that, it will going to give error in some condition

I think the way to do this while using Reactive form protocols is upon your button click is to .setValue('').
So instead your send message would look like this.
sendMessage() {
// Operations here prior to resetting value...
this.userObjectField.setValue('');
}

Related

How to get value of mat-option selected?

I've been trying to find a way to pull the value of a selected mat-option with this html/ts pairing.
html
<mat-form-field appearance="outline" floatLabel="always">
<mat-label>TRA Type</mat-label>
<mat-select
placeholder="TRA Type"
id="traType"
name="traType"
data-qa="new-tra"
[(ngModel)]="formSelect"
required>
<mat-option id="Regular" name="Regular" value="Regular">Regular</mat-option>
<mat-option id="Unitary" name="Unitary" value="Unitary">Unitary</mat-option>
</mat-select>
<mat-hint>Required</mat-hint>
</mat-form-field>
ts
formSelect: string;
traType = <any>{};
When propping up the page locally, this.traType.value doesn't prop up the value of the selected mat-option. It comes up as undefined when the expected result would be either "Regular" or "Unitary."
this.traType.value doesn't show the selected value as you miss [formControl] Input binding in <mat-select> element.
Solution:
Add [formControl]="traType" in <mat-select> element.
<mat-select placeholder="TRA Type"
id="traType"
name="traType"
[formControl]="traType"
data-qa="new-tra"
required>
..
</mat-select>
Solution in StackBlitz
Note: You are recommended to remove [(ngModel)] binding if you use [formControl] as it has been deprecated in Angular v6.
Reference
Form field features (Sample in HTML)

Set initial value to a Toggle of a form in Angular Material within HTML

I am working with a simple form:
HTML
<mat-card>
<form (submit)="onAddBet(betForm)" #betForm="ngForm">
<mat-form-field>
<textarea #description="ngModel" matInput rows="6" placeholder="Description" name="description" ngModel
required></textarea>
<mat-error *ngIf="description.invalid">Please enter a Bet Description</mat-error>
</mat-form-field>
<mat-slide-toggle #privacy="ngModel" name="privacy" ngModel>Private</mat-slide-toggle>
<mat-slide-toggle #comments="ngModel" name="comments" ngModel>Allow comments</mat-slide-toggle>
<button mat-raised-button color="primary" type="submit">
CREATE
</button>
</form>
</mat-card>
If I press submit without touching any field of the form I get all the fields empty as it should be expected but I would like to get instead of the status of the form, meaning all the fields as "" but in the fields "privacy" and "comments" as false (boolean) (the default appearance of the toggles is as not marked).
I know that this could be easily done by Typescript from the component following the method:
Typescript
onAddBet(form: NgForm) {
if (!form.value.privacy) {
form.value.privacy = false;
console.log(form.value);
} else console.log(form.value);
if (form.invalid) return;
form.resetForm();
}
But I was wondering if there is any HTML attribute to run the same code avoiding to use Typescript
How could I do it?
You can initialize your ngModel in your HTML by using ngModel with a one-way binding
<mat-slide-toggle #privacy="ngModel" name="privacy" [ngModel]="false">Private</mat-slide-toggle>
<mat-slide-toggle #comments="ngModel" name="comments" [ngModel]="false">Allow comments</mat-slide-toggle>
Then in your component
onAddBet(form: NgForm) {
console.log(form.value);
if (form.invalid) return;
form.resetForm();
}
As per the documentation of slide-toggle you can use [checked]="checked" in HTML.

Disabled Datepicker is validated

I have a form class with several inputs. There is a Checkbox, which enables/disables Datepicker input (Datepicker is not required) based on boolean variable (switchDate). Even if the Datepicker is disabled, it will be still validated and causing whole form to have status invalid.
My submit form button condition is: [disabled]="productForm.invalid". Unfortunately this button will be disabled without valid Datepicker field.
My question is: how to validate Datepicker field only if it is enabled?
PS I am newbie to Angular
I've tried to change submit button disabled criteria to focus on other fields errors, but this way it will pass any input in Datepicker
I was trying to find some method to check if the Datepicker field is enabled/disabled inside submit button condition, but no luck here
<input type="checkbox"
name="switcherChk"
id="switcherChk"
checked="true"
(change)="changeDatepickerVisibility()" />
<mat-form-field class="example-full-width">
<input matInput [matDatepicker]="picker"
[min]="todaysDate"
placeholder="Example text"
formControlName="userDate"
[attr.disabled]="switchDate ? '' : null"
required = false
>
<mat-datepicker-toggle matSuffix [for]="picker">
<mat-icon matDatepickerToggleIcon>keyboard_arrow_down</mat-icon>
</mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
<mat-error *ngIf="productForm.controls['userDate'].invalid">
Date should be greater or equal to current date.
</mat-error>
</mat-form-field>
Resolved this way (on the Component side):
private changeUserDateValidators(): void{
var dateControl = this.productForm.get(this.UserDateField);
if (this.switchDate) {
dateControl.setValidators(Validators.required);
}
else {
dateControl.clearValidators();
}
dateControl.updateValueAndValidity();
}
Depending on what you want to achieve, you can replace Validators.required to your custom validator.

Reset Angular Formly Form Validations on click event

I am implementing dynamic forms using the angular formly module and It's working fine. What functionality I need is Initially there should be a select box which contains multiple options, Based on selection different form fields should be displayed. As I explained I have Implemented and it's working, here what my problem is If I select option 1 and If I submit the form without filling fields, form displaying validation errors that is also cool. But when I select option 2 form fields are changing, but by default, all required fields are showing errors. How can I resist this? Please suggest me.
html
<div class="row">
<mat-form-field class="col-lg-2">
<mat-select placeholder="Form For" (selectionChange)="getSelectedFormName($event)">
<mat-option value="uf001">UF001</mat-option>
<mat-option value="uf002">UF002</mat-option>
<mat-option value="uf003">UF003</mat-option>
</mat-select>
</mat-form-field>
<div class="col-lg-4">
<button type="button" class="btn btn-default btn-one" (click)="getDynamicForm()">GET FORM</button>
</div>
</div>
<form [formGroup]="form" (ngSubmit)="submit(model)" >
<formly-form [model]="model" [fields]="fields" [form]="form" *ngIf="isFormTypeSelected" >
</formly-form>
<button type="submit" class="btn btn-success">Submit</button>
</form>
ts file
getSelectedFormName(eve) {
this.isFormSaved = false;
this.form = new FormGroup({});
this.fields=[];
this.model = {};
this.parentFormName = eve.value;
}
getDynamicForm() {
this.isFormSaved = false;
this.savedFields=[];
this.getDynamicFormBasedOnSelection(this.parentFormName);
//fields getting from api call
}
getDynamicFormBasedOnSelection(formName: string) {
this.auth.getDynamicFormBasedOnSelction(formName, this.userAgencyCode).subscribe(
(result) => {
const str = JSON.stringify(result);
this.fields = JSON.parse(str);
this.isFormTypeSelected = true;
this.addEvents(this.fields);
});
}
Here I'm providing my screens which are for better understanding
Actually form.reset() just reset the form values. You need to reset the form directive too. for eg.
<form [formGroup]='authForm' (submit)='submitForm(formDirective)' #formDirective="ngForm" class="is-mat-form">
<mat-form-field>
<input matInput placeholder="Email ID" formControlName='login'>
<mat-error *ngIf="authForm.controls.login.hasError('required')">
Email is required
</mat-error>
<mat-error *ngIf="authForm.controls.login.hasError('email')">
Please enter a valid email address
</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput type="password" formControlName='password' placeholder="Password">
<mat-error *ngIf="authForm.controls.password.hasError('required')">
Password is required
</mat-error>
<mat-error *ngIf="authForm.controls.password.hasError('minlength')">
Password must be minimum 6 digit long.
</mat-error>
</mat-form-field>
and .ts file is
submitForm(formDirective: FormGroupDirective){
if (this.authForm.invalid) {
console.log('form submitted')
this.authForm.reset()
return;
}
this will reset the form values only, to reset the form error we need to reset the formdirective as well.
submitForm(formDirective: FormGroupDirective){
if (this.authForm.invalid) {
console.log('form submitted')
this.authForm.reset()
formDirective.resetForm();
return;
}

Save and bind to the Id of a drop-down selection, but display the Value in Angular Material

This might be a stupid question with a very simple answer, but after a week of coding I feel fried and can't figure it out.
How can I bind to the Id of a selection, but display the string representation of the value? I.e., I have a drop-down that display the names of Customers, but I want to save the Id for DB purposes.
My selection item has two properties: customer.Display (Name), and customer.Id.
How can I do the binding to save my Id to [(ngModel)]="loadDataService.selectedLoad.CustomerId, but display my Display in the drop-down (it already displays the Display, so that is covered):
<mat-form-field>
<input type="text" placeholder="Customer Search" id="CustomerId" name="CustomerId" aria-label="Number" matInput [formControl]="myCustomerSearchControl"
[matAutocomplete]="auto" [(ngModel)]="loadDataService.selectedLoad.CustomerId" (keyup)="onCustomerSearch($event)">
<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
<mat-option *ngFor="let customer of customerArray" [value]="customer.Display">
{{ customer.Display }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
When you use the autocomplete, you have a optionSelected event. You need to use that to find your selected option.
<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" (optionSelected)="setServiceId($event)">
...
</mat-autocomplete>
Then, in your component, you must implement that function :
setServiceId(dislay: string) {
const id = this.customerArray.find(c => d.Display === display).id;
this.loadDataService.selectedLoad.CustomerId = id;
}
This way of doing assumes you have unique customer displays. If not, you will need to use this function, with the previous HTML + this HTML :
setServiceId(customer: any) {
this.loadDataService.selectedLoad.CustomerId = customer.id;
}