The problem here is supposed to be simple but I'm not able to initialize an input field for a reactive form and have that control as valid.
lets say I have this code:
@Component({
selector: 'app-profile-editor',
templateUrl: './profile-editor.component.html',
styleUrls: ['./profile-editor.component.css']
})
export class ProfileEditorComponent {
profileForm = this.fb.group({
firstName: string,
lastName: string,
address: this.fb.group({
fName: ['initial value', [Validators.required]],
city: ['', [Validators.required]],
state: [''],
zip: ['']
}),
});
constructor(private fb: FormBuilder) { }
}
And in the template I have lets say:
<input [(ngModel)]="firstName" formControlName="fName" />
The problem is that setting the default value this way is not working:
fName: ['initial value', [Validators.required]],
second way not working:
fName: new FormControl('initial value', [Validators.required])
third way is in the template doing this is not working as well:
<div>
<input [(ngModel)]="firstName" formControlName="fName" [value]="'default value'"/>
</div>
A fourth way to do it is:
this.address.controls['fName'].setvalue('default value');
this.address.controls['fName'].updateValueAndValidity();
So when I try all these combination or one of them at a time, and go in the debugger and verify what is the value of: this.address.controls['fName'].value it gives me an empty value --> ''
as a result even if in my form the field is initially populated and I have to provide the others fields then because of this field my form is not valid I then it's not showing my save button as enabled.
can some one explain why this behavior or explain what is the right way to go with this ?
Note: I'm just giving here a small code example as a hint, because my real code is part of a bigger and a proprietary angular 6 application.
I've to clean up this example but here is one using: <input type="text" class="form-control" id="username" formControlName = "username" [(ngModel)]="name">
https://stackblitz.com/edit/angular-reactive-forms-jhg6ds?file=app%2Fapp.component.ts
(will update this example later.)
In this case, the default value is not shown, because I think kind of a concurrency with ngModel content, so I want to set that default value event if the content of ngModel is empty (example when creating a empty form, the user has to find some field already filled (and then valid))
formControlName
and[(ngModel)]
on the same element. That's kind of redundant and Angular has depricated it in V6. Angular will get rid of it in V7 – SiddAjmera[(ngModel)]
in your template:<input formControlName="fName" />
– SiddAjmera