I know questions like this has been asked before but unfortunately those didn't work out for me.
So I am working in angular 7 I created a reactive form field that contain firstname, lastname and some other details and every field is disabled by default and also have their own edit button.
So what I want is to enable and disable the particular field for which I click the edit button rest other fields should remain disabled.
May be I should create my own custom directive but that's really confusing for me.
So is there any easy way to achieve this? or if custom directive is the only easy way to achieve this then please help out with some link or code to do this.
Right now I created a variable of boolean type and by using this variable I enable and disable it, but problem with this approach is I have to created separate variable for each field in order to avoid confusion but I don't think that is count under the best approach. I shared my code for better understanding.
component.ts
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
profileForm: FormGroup;
userData: User
isDisable :boolean = true
constructor() { }
ngOnInit() {
this.userData = JSON.parse(localStorage.getItem("user data"));
this.profileForm = new FormGroup({
'firstname': new FormControl({value: this.userData.firstname, disabled: this.isDisable}, Validators.required),
'lastname': new FormControl({value: this.userData.lastname, disabled: this.isDisable}, Validators.required)
})
}
onEdit(value:string) {
this.isDisable=!this.isDisable
console.log(this.isDisable);
if(!this.isDisable) {
this.profileForm.controls[value].enable()
}
if(this.isDisable) {
this.profileForm.controls[value].disable()
}
}
onSubmit() {
console.log(this.profileForm.value)
}
}
component.html
<div class="col-12">
<div class="form-section">
<form
class="login-form"
[formGroup]="profileForm"
(ngSubmit)="onSubmit()">
<div class="row mb-4 no-gutters">
<div class="col-4 property">
First Name:
</div>
<div class="col-7 value">
<div class="form-group m-0">
<input
type="text"
class="form-control"
name="firstname"
formControlName="firstname"
id="">
</div>
</div>
<div class="col-1 value">
<button
type="button"
class="btn btn-primary"
(click)="onEdit('firstname')">
edit
</button>
</div>
</div>
<div class="row mb-4 no-gutters">
<div class="col-4 property">
Last Name:
</div>
<div class="col-7 value">
<div class="form-group m-0">
<input
type="text"
class="form-control"
name="lastname"
formControlName="lastname"
id="">
</div>
</div>
<div class="col-1 value">
<button
type="button"
class="btn btn-primary"
(click)="onEdit('lastname')">
edit
</button>
</div>
</div>
<button
class="btn btn-primary mt-4"
[disabled]="!profileForm.dirty"
type="submit">Submmit</button>
</form>
</div>
</div>