Amit Shaw
Amit Shaw

Reputation: 221

How to set default value in formControl in angular 5

If there is no data in the table, I am getting undefined from service but I want to display default value in formControl in that case. if data is there then working fine...Please help me and suggest what I need to do.

Upvotes: 22

Views: 101016

Answers (3)

Suren Srapyan
Suren Srapyan

Reputation: 68635

When you create the group and controls inside it, you can also initialize them.

fb is the FormBuilder

fb.group({
   yourControl: [0, Validators.required] // '0' is the default value
});

Upvotes: 29

Samuel Diogo
Samuel Diogo

Reputation: 789

Using FormControl constructor:

myFormGroup = new FormGroup({
    mycontrol: new FormControl('myDefaultValue'),
});

doc source: Angular.io - Initializing Form Controls

Upvotes: 1

Krishna Rathore
Krishna Rathore

Reputation: 9687

You can try with default value in form control.

myForm: FormGroup;
ngOnInit() {
    this.myForm = this.fb.group({
        name: ["test", [Validators.required, Validators.maxLength(30)]],
        address: this.fb.group({
            pin: ["123456", Validators.required]
        })
    });
}

Upvotes: 5

Related Questions