Reputation: 817
my issue is that I have a MatInput as follows:
<input matInput [(ngModel)]="name" i18n-placeholder="@@Placeholder" placeholder="Your name" [formControl]="InputControl" value="{{ fieldName }}">
In the correspoding component I declared fieldName: string;
and I am setting the value in the ngOnInit()
method:
ngOnInit() {
this.fieldName = "VALUE"; // obtained from server so it may differ
if(this.fieldName.startsWith("PREFIX")) { // if value starts with a given prefix I want to remove it
this.fieldName = this.fieldName.substr(3);
}
}
The thing is that it's actually working well (value gets displayed properly), but as soon as I want to submit the MatDialog form it tells me that I can't submit an empty form! Thats because I added a 'required' validator:
InputControl = new FormControl("", [Validators.required]);
So there is a value in the input field, but apparently Angular doesn't notice it? If I add a space to the value and delete it afterwards the value is exactly the same, but then it doesn't throw any errors. Does anyone know how to fix this? It's really annoying.
Upvotes: 2
Views: 1275
Reputation: 387
In my case I mistakenly added the Validator required like this:
let numberControl = new FormControl(initialValue, [Validators.requiredTrue])
requiredTrue => Validator that requires the control's value be true.
I was setting up number values, which always triggered the required error. Instead, I should do this:
let numberControl = new FormControl(initialValue, [Validators.required])
required => Validator that requires the control to have a non-empty value.
Upvotes: 0
Reputation:
value
attributes are worthless in Angular.
If you want to give your control a value, do it through the control itself :
<input matInput [(ngModel)]="name" i18n-placeholder="@@Placeholder" placeholder="Your name" [formControl]="InputControl">
ngOnInit() {
this.fieldName = "VALUE"; // obtained from server so it may differ
if(this.fieldName.startsWith("PREFIX")) {
this.fieldName = this.fieldName.substr(3);
}
// w/ form control
this.InputControl.setValue(this.fieldName);
// w/ template driven
this.name = this.fieldName;
}
Upvotes: 1