not set ouput value in reactive form - angular9 - javascript

I have a form and in this for I use the from array :
private InitialFrom(): void {
this.addElectricMoneyFG = this.fromBuilder.group({
locales: this.fromBuilder.array([])
})
}
and i have a component , that have output by this value :
<multi-language-data-form
[selectLanguage]="selectLanguage"
[fields]="fields"
sticy="true"
(formValue)="setValue($event)"
></multi-language-data-form>
and it return this value from output :
locales:
0:
languageId: 1
moreAccountInfo: "gh"
name: "ghgh"
1:
languageId: 2
moreAccountInfo: "gh"
name: "ghgh"
and when i want to update the form from that value it not set value from the locals :
setValue(value): void {
this.addElectricMoneyFG.patchValue({ ...value });
}
whats the problem ? how can i set the value from the form ???

You do not need to create a formBuilder inside the main formBuilder, you can just do this:
private InitialFrom(): void {
this.addElectricMoneyFG = this.formBuilder.group({
locales: []
})
}
To patch the value to the form, you can pass LanguageId from (formValue) event, then get the value with find, and patch desired value to the FormGroup.
To use patchValue method, you need to precise the form field as key of the object parameter you pass to patchValue(). for example here it's "locales"
setValue(languageId: number): void {
var getLocale = this.fields.find(x => x.languageId == languageId);
this.addElectricMoneyFG.patchValue({ locales: getLocale });
}

Related

Angular Form Control Dynamic Parameter

So I have a form that I need to add validators to and some of the controls are required only if a certain condition is matched by another control. What is a good way to do this. I originally made a custom validator function that I passed in a parameter to the function to determine if it should be required, but it keeps the original value of the parameter not matter if I update other controls in the form.
public static required(bookType: BookType, controlKey: string) {
return (control: AbstractControl): ValidationErrors | null => {
if(this.isRequired(bookType,controlKey)){
return !control.value? {required: true} : null
}
return null;
}
}
the form book type is originally DIGITAL and I change the book type to PRINT it stays DIGITAL.
This feels like it should stay a form-control validator since I am validating one value, not the group.
What would be the best way to make this work?
You need to implement a cross fields validator. So you will be able to play with values of these fields inside the validator function. Details: https://angular.io/guide/form-validation#cross-field-validation
const deliveryAddressRequiredValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
const bookType = control.get('bookType');
const deliveryAddress = control.get('deliveryAddress');
if (bookType && deliveryAddress && bookType.value === 'PRINT' && Validators.required(deliveryAddress)) {
return { deliveryAddressRequired: true };
}
// no validation for book type DIGITAL
return null;
};
Usage:
this.form = this.formBuilder.group({
bookType: ['', [Validators.required]],
deliveryAddress: [''],
}, {validators: deliveryAddressRequiredValidator});
To display error in the template use: form.errors?.deliveryAddressRequiredValidator

Pass a dynamic parameter in reactive form custom validator

I would like to pass a variable as a parameter in a custom validator like this
newSimulation: new FormControl('', [uniqNameValidator(this.options)])
Then use it in my custom validator
export function uniqNameValidator(list: any): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const simulationFlatList = list.map(val => val.closingPeriodSimulationName)
return simulationFlatList.indexOf(control.value) > -1 ? { message: "simulation exists" } : null;
}
}
The issue with this is that this.options is always empty. I initialize it to [] but when user interacts with the form ( first field ) I update it to an array of string, I think that the custom validator does not recheck the value of this.options ?
In this case how to pass a variable in custom validator ?
this may work, bind the function to component newSimulation: new FormControl('', [uniqNameValidator.bind(this)]) then in the function you can access this.options

How to traverse a typed array?

I have the following class model in my application Angular:
export class IItemsModel {
public description: string;
public itemDetail: IItemDetailModel;
public itemCategories: IItemCategoriesModel[]; // array of IItemCategoriesModel
}
export class IItemCategoriesModel {
public id: string | number;
public description: string;
}
And my Controller:
itemModel: IItemsModel;
selectedCategories: any[] = [];
ngOnInit() {
this.itemModel = new IItemsModel();
this.itemModel.itemCategories = [];
}
onSubmit(form: NgForm) {
// here I format the data
}
In the template I have a multiple select where I fill an array with the id's of the chosen categories.
[25, 38] // selectedCategories
Problem, I'm using ngModel to link the form with the controler, but to send the pre-filled data to the API, I have to format the id's to the model format, that is:
{
...,
itemDetail: 'something',
itemCategories: [
{ id: any Id },
{ id: other Id }
]
}
I try to format the data as follows in the onSubmit() method:
for(let i=0; i<this.selectedCategories.length; i++) {
this.itemModel.itemCategories[i].id = this.selectedCategories[i];
}
But I get the error:
TypeError: Cannot set property 'id' of undefined # undefined:undefined
How could you be formatting the itemCategories to be able to send the data correctly to the API?
Use forEach to iterate instead of for loop.
this.selectedCategories.forEach(f => {
this.itemModel.itemCategories.push({ id: f, description: '' })
});
Since your selectedCategories object is an array of numbers, it doesn't have id property in it. That's why you're getting errors.
Working demo at StackBlitz.
Click the button and check the console log.

Angular: How to get default #Input value?

We are developing components and when using them, we would like to use the same mechanism like for DOM nodes to conditionally define attributes. So for preventing attributes to show up at all, we set the value to null and its not existing in the final HTML output. Great!
<button [attr.disabled]="condition ? true : null"></button>
Now, when using our own components, this does not work. When we set null, we actually get null in the components #Input as the value. Any by default set value will be overwritten.
...
#Component({
selector: 'myElement',
templateUrl: './my-element.component.html'
})
export class MyElementComponent {
#Input() type: string = 'default';
...
<myElment [type]="condition ? 'something' : null"></myElement>
So, whenever we read the type in the component, we get null instead of the 'default' value which was set.
I tried to find a way to get the original default value, but did not find it. It is existing in the ngBaseDef when accessed in constructor time, but this is not working in production. I expected ngOnChanges to give me the real (default) value in the first change that is done and therefore be able to prevent that null is set, but the previousValue is undefined.
We came up with some ways to solve this:
defining a default object and setting for every input the default value when its null
addressing the DOM element in the template again, instead of setting null
<myElement #myelem [type]="condition ? 'something' : myelem.type"></myElement>
defining set / get for every input to prevent null setting
_type: string = 'default';
#Input()
set type(v: string) {if (v !== null) this._type = v;}
get type() { return this._type; }
but are curious, if there are maybe others who have similar issues and how it got fixed. Also I would appreciate any other idea which is maybe more elegant.
Thanks!
There is no standard angular way, because many times you would want null or undefined as value. Your ideas are not bad solutions. I got a couple more
I suppose you can also use the ngOnChanges hook for this:
#Input()
type: string = 'defaultType';
ngOnChanges(changes: SimpleChanges): void {
// == null to also match undefined
if (this.type == null) {
this.type = 'defaultType';
}
}
Or using Observables:
private readonly _type$ = new BehaviorSubject('defaultType');
readonly type$ = this._type$.pipe(
map((type) => type == null ? 'defaultType' : type)
);
#Input()
set type(type: string) {
this._type$.next(type);
}
Or create your own decorator playground
function Default(value: any) {
return function(target: any, key: string | symbol) {
const valueAccessor = '__' + key.toString() + '__';
Object.defineProperty(target, key, {
get: function () {
return this[valueAccessor] != null ? this[valueAccessor] : value
},
set: function (next) {
if (!Object.prototype.hasOwnProperty.call(this, valueAccessor)) {
Object.defineProperty(this, valueAccessor, {
writable: true,
enumerable: false
});
}
this[valueAccessor] = next;
},
enumerable: true
});
};
}
which you can use like this:
#Input()
#Default('defaultType')
type!: string;
Just one more option (perhaps simpler if you don't want to implement your own custom #annotation) based off Poul Krujit solution:
const DEFAULT_VALUE = 'default';
export class MyElementComponent {
typeWrapped = DEFAULT_VALUE;
#Input()
set type(selected: string) {
// this makes sure only truthy values get assigned
// so [type]="null" or [type]="undefined" still go to the default.
if (selected) {
this.typeWrapped = selected;
} else {
this.typeWrapped = DEFAULT_VALUE;
}
}
get type() {
return this.typeWrapped;
}
}
If you need to do this for multiple inputs, you can also use a custom pipe instead of manually defining the getter/setter and default for each input. The pipe can contain the logic and defaultArg to return the defaultArg if the input is null.
i.e.
// pipe
#Pipe({name: 'ifNotNullElse'})
export class IfNotNullElsePipe implements PipeTransform {
transform(value: string, defaultVal?: string): string {
return value !== null ? value : defaultVal;
}
}
<!-- myElem template -->
<p>Type Input: {{ type | ifNotNullElse: 'default' }}</p>
<p>Another Input: {{ anotherType | ifNotNullElse: 'anotherDefault' }}</p>

Parsing Map with null value in Typescript from JSON

I am using the following class in Typescript to parse Employee data received as JSON using TypedJson.parse()
#JsonObject()
export class Employee {
#JsonMember()
public name: string;
#JsonMember()
public columns: { [name: string]: any };
}
columns is a Map<String, Object> sent from Spring backend.
While parsing TypedJson ignores all the keys with value as null and thus no key values pair objects of the form myKey: null are created. I do not have options of replacing all null with ''
How to get those null values parsed to objects with null values?
So, I've seen the code of TypedJson - in current version 0.1.7 it is bug, but in the repository this bug is fixed, but not published yet.
So you can use workaround until next release just adding = null! as property default value:
#JsonObject()
export class Employee {
#JsonMember()
public name: string = null!;
#JsonMember()
public columns: { [name: string]: any } = null!;
}
As #JonnyAsmar suggested JSON.parse works for this scenario.
I was previously doing
this._http.get(`${HTTP_URL}/${params.EmployeeId}/EmployeeData`, { params: params })
.map(response => TypedJSON.parse(response.text(), Employee)
})
.catch(this.handleError);
as a workaround I am now doing:
this._http.get(`${HTTP_URL}/${params.EmployeeId}/EmployeeData`, { params: params })
.map(response => {
let obj:JSON = JSON.parse(response.text());
return obj;
})
.catch(this.handleError);

Categories