简体   繁体   中英

What are the techniques for debugging angular components that are not displaying on the screen?

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:

  • How is an angular material input field placed inside a <form> element
  • When something is not showing up on the screen what tools does angular offer to debug the cause. In my case I see no error message just that the component is not displayed.

I 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.

  • Template Driven where angular creates the FormControl objects
  • Reactive where the developer must create the FormControl in the component class

In 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM