My current tech stack includes an Angular application with the .NET 6.0 framework, running on Angular version 13.1.2, Node version 16.13.1, and EMCAScript 5.
I have defined a Person class in TypeScript as follows:
export class Person {
private _name: string = '';
constructor() {
}
public get name(): string {
return this._name;
}
public set name(value: string) {
this._name = value;
}
}
When I compile my code, it generates a person.model.js file where I suspect Object.defineProperties is not functioning as expected.
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Person = /** @class */ (function () {
function Person() {
this._name = '';
}
Object.defineProperty(Person.prototype, "name", {
get: function () {
return this._name;
},
set: function (value) {
this._name = value;
},
enumerable: true,
configurable: true
});
return Person;
}());
exports.Person = Person;
//# sourceMappingURL=person.model.js.map
While trying to update my Reactive form using an object, I notice that no data gets updated. Upon debugging, I observe that only the '_name' property appears in the 'Object.Keys' array.
this.personForm.get('person')?.patchValue(person);
The Reactive form setup looks like this:
return formBuilder.group({
person: formBuilder.group({
name: [
'',
[
Validators.required
]
]
})
});
However, when I utilize 'Object.DefineProperty' in my class, the aforementioned issue seems to be resolved, and the 'Name' property correctly shows up in the 'Object.Keys' array.
export class Person {
private _name: string = '';
constructor() {
Object.defineProperty(this, 'name', {
set: function (value: string) {
this._name = value;
},
get: function () {
return this._name;
},
enumerable: true
})
}
}
Should I include Object.defineProperties in the .ts file, or could it be that my application is not utilizing the generated .js files properly?
EDIT:
Component
export class PersonComponent implements OnInit {
personForm!: FormGroup;
constructor(
private _fb: FormBuilder) {}
private CreateFormGroup(formBuilder: FormBuilder): FormGroup {
return formBuilder.group({
person: formBuilder.group({
name: [
'',
[
Validators.required
]
]
})
});
}
ngOnInit(): void {
this.personForm = this.CreateFormGroup(this._fb);
}
setPerson(person: Person) {
if (person != undefined) {
this.personForm.get('person')?.patchValue(person);
}
}
}
HTML:
<mat-card class="mat-elevation-z10">
<mat-card-title>Person</mat-card-title>
<mat-card-content>
<form [formGroup]="personForm">
<div formGroupName="person">
<mat-form-field class="person-name">
<input id="name" matInput aria-label="name" type="text" formControlName="name" autofocus required />
<mat-placeholder class="placeholder">name</mat-placeholder>
</mat-form-field>
</div>
<br />
</form>
</mat-card-content>
</mat-card>
<app-person-selection (personEvent)="setPerson($event)"></app-person-selection>