I have the following code
<form #createForm="ngForm">
<mat-form-field>
<mat-select placeholder="Favorite food"
matInput
[ngModel]
food="food"
#food="ngModel" required>
<mat-option *ngFor="let food of foods" [value]="food.value">
{{ food.viewValue }}
</mat-option>
</mat-select>
</mat-form-field>
</form>
<button [disabled]="!createForm.valid">submit</button>
Since I want the "selection" is a required field, the "submit" button should be disabled when the form is rendered. However, the "submit" button is enabled when the form is displayed. What is the problem?
It is possible to disable the entire select or individual options in the select by using the disabled property on the <select> or <mat-select> and the <option> or <mat-option> elements respectively.
One can reset an Angular Material Select component by adding a mat-option with no value attribute. The first, “All”, option has no value and resets the MatSelect.
which out put looks like: It fades out the text and the lining below get changes, is it possible to make it readonly? You can replace the mat-select form field with a input box and bind input box data with mat-select data.
This works for me when I (a) use a name
attribute and (b) use the two-way ngModel
binding syntax.
i.e. Instead of this
<mat-select placeholder="Favorite food" matInput [ngModel] food="food" #food="ngModel" required>
use this:
<mat-select name="food" placeholder="Favorite food" [(ngModel)]="food" required>
for validation in angular 5 use reactive forms. refer this
*** componenet.ts *******
import { FormControl, Validators, FormBuilder, FormGroup, ReactiveFormsModule, NgForm } from '@angular/forms';
export class Test implements OnInit{
foodform:FormGroup;
constructor(){}
ngOnInit() {
// create form group of controls
this.foodform = new FormGroup({
favoriteFood: new FormControl('', [Validators.required])
});
}
}
**** Component.html************
<form #createForm="ngForm" [formGroup]="foodform ">
<mat-form-field>
<mat-select placeholder="Favorite food"
matInput
[ngModel]
food="food"
#food="ngModel" formControlName="favoriteFood">
<mat-option *ngFor="let food of foods" [value]="food.value" >
{{ food.viewValue }}
</mat-option>
</mat-select>
<mat-error *ngIf="foodform.controls['favoriteFood'].hasError('required') && foodform.controls['favoriteFood'].pristine">
Required Message
</mat-error>
</mat-form-field>
</form>
use [formGroup]
and formControlName
in your html form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With