简体   繁体   中英

default value of form control doesn't show

I am trying to give any formcontrol 's in my whole project a default value, It doesn't show in the html. Here is an example:

this my ts file

 import {FormBuilder, FormGroup, FormArray, Validators, NgForm} from   
 '@angular/forms';

template = this.fb.group({
templateName: ['name', [Validators.required]]})
constructor(private fb: FormBuilder){}

my html

  <form [formGroup]="template" #formDirective="ngForm" class="col-lg-4 col-md-4 col-con">

          <input matInput placeholder="Template Name"
   maxlength="255" formControlName="templateName" value=""
                 required>
   </form>

my module

    imports: [
BrowserModule,
CommonModule,
FormsModule,
HttpClientModule,
AppRoutingModule,
RouterModule,
ReactiveFormsModule]

just remove this attribute value=""

 <form [formGroup]="template" #formDirective="ngForm" class="col-lg-4 col-md-4 col-con">
     <input matInput placeholder="Template Name"   formControlName="templateName"  >
 </form>

I'm also recommend to remove maxlength="255",required and use Validators.required and Validators.maxLength

templateName: ['name', [Validators.required,Validators.maxLength(255)]]

Or you can add ngValue

<input matInput placeholder="Template Name"
   maxlength="255" formControlName="templateName" [ngValue]="name" required>

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