I am new to angular and angular material I have very simple view
<div class="mat-headline">Product Inventory Search</div>
<form (ngSubmit)="search()">
<mat-form-field>
<mat-label>Product</mat-label>
<input matInput type="text" [formControl]="product" />
</mat-form-field>
</form>
When it display I do not see any input field as seen blow
If I remove the form
element surrounding mat-form-field
like below
<div class="mat-headline">Product Inventory Search</div>
<mat-form-field>
<mat-label>Product</mat-label>
<input matInput type="text" [formControl]="product" />
</mat-form-field>
It works I can see the product field as show below
Two questions:
<form>
elementI figured it out after a lot of stumbling in the dark and on blog sites.
For each form element on the from angular expects there to a FromControl
object to store the state of the form element. If there is no FormControl
angular 10 is not rendering the form element since it has no place to manage the state of the element. There are two ways to create the form controls.
FormControl
objectsFormControl
in the component classIn the case of a reactive form there can be multiple form elements therefore a FormGroup
object must be built by the developer and associated with form. The code below works.
<form [formGroup]="searchForm" (ngSubmit)="search()">
<mat-form-field>
<mat-label>Product</mat-label>
<input matInput type="text" formControlName="product" />
</mat-form-field>
<button mat-button color="primary">search</button>
</form>
The main change from my incorrect version is the [formGroup]="searchForm
and formControlName="product"
instead of [formControl]="product"
My misunderstanding of things is now cleared up but I am still looking for ways to more effectively debug issues like this in the future.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.