Reputation: 129
I have scenario where iam having the forms with the name field, where i will pass the default value and i need to make this as read only or disabled and also i can able to append the value with this. eg: Room-123 Room-is the default value need to read only or disabled 123-can be append with the room and it can be editable.can anyone give a solution for this.
public RoomValue: string='Room';
public roomDiagForm = this.formBuilder.group({
id:this.formBuilder.control(''),
name: this.formBuilder.control(this.RoomValue, Validators.required),
type: this.formBuilder.control('', Validators.required),
locationId: this.formBuilder.control(this.location, Validators.required),
});
this is my code.
Upvotes: 0
Views: 284
Reputation: 7294
You can try this one.
Call a function when you find value can change and check your conditions
.ts file
import { Component } from "@angular/core";
import { FormGroup, FormBuilder } from "@angular/forms";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
contactForm: FormGroup;
defaultName = "Room";
constructor(private formBuilder: FormBuilder) {
this.createContactForm();
}
createContactForm() {
this.contactForm = this.formBuilder.group({
fullName: [this.defaultName]
});
}
checkFullname(event) {
let readOnlyLength = this.defaultName.length;
let enteredValue = this.contactForm.controls["fullName"].value;
let keypressed = event.which; // 8 => backspace, 46 => delete
if (
(keypressed == 8 && enteredValue.length <= readOnlyLength) ||
(keypressed == 46 && enteredValue.length <= readOnlyLength)
) {
event.preventDefault();
}
if (keypressed != 0 && event.target.selectionStart < readOnlyLength) {
event.preventDefault();
}
}
}
.html
<form [formGroup]="contactForm" (ngSubmit)="onSubmit()">
<input type = "text" name = "fullName" placeholder = "Your full name" formControlName="fullName" (keydown)="checkFullname($event)" (keyup)="checkFullname($event)" (paste)="checkFullname($event)" (cut)="checkFullname($event)">
<br/>
<input type = "submit" value = "Send">
</form>
working link
https://stackblitz.com/edit/angular-yub6rf?embed=1&file=src/app/app.component.html
Note: I was also searching to club possible events together as all are calling same function but I am not able to do it.
I found a github link check this as well if you can find a way
https://github.com/angular/angular/issues/6675
Upvotes: 1
Reputation: 169
In Angular reactive forms, you can instantiate a new control in the form group with the disable attribute set to true Example :
this.formBuilder.group({
name : new FormControl({value: '', disabled: true})
})
you can also conditionally disable using the below code
this.formBuilder.get('name').disable();
this.formBuilder.get('name').enable();
you will also have to use the below code
"this.formBuilder.updateValueValidity()"
after the disabling or enabling to apply the changes.
Upvotes: 0