Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a formControl readonly

How to make a formControl in angular readonly

I know i can do it in html like

<input type="text" formControlName="xyz" readonly /> 

how to do it from JS Code and not html i.e in a model driven way

like image 659
Ankit Raonka Avatar asked Aug 02 '17 05:08

Ankit Raonka


People also ask

How do I make FormControl readonly?

We use READONLY attribute to prevent user from type/select the form control but we get value from the input. We use DISABLED attribute to prevent user from type/select the form control and we dont get value from the input.

What is difference between FormBuilder and FormControl?

In Angular, a reactive form is a FormGroup that is made up of FormControls. The FormBuilder is the class that is used to create both FormGroups and FormControls.


1 Answers

If you are using Reactive Forms you can assign it dynamically like in the example code below (email field)

    this.registerForm = this.formBuilder.group({           first_name: ['', Validators.required],           last_name: ['', Validators.required],           email: new FormControl({value: null, disabled: true}, Validators.required),           password: ['', Validators.compose([Validators.required, Validators.email])],           confirm_password: ['', Validators.required],     }); 

If you want to get all the values including disabled controls you should use:

    this.registerForm.getRawValue(); 

View method comment on source code

    /**        * The aggregate value of the `FormGroup`, including any disabled controls.        *        * If you'd like to include all values regardless of disabled status, use this method.        * Otherwise, the `value` property is the best way to get the value of the group.        */       getRawValue(): any; 

Enjoy coding!

like image 73
ErvTheDev Avatar answered Sep 20 '22 11:09

ErvTheDev