Attempting to bind to a property of a nested object using [(ngModel)], but facing the challenge that the path to the property is dynamically set.
Consider the following three classes:
class A {
p1: C
constructor() {
p1 = new C("A")
}
}
class B {
p2: C
constructor() {
p2 = new C("B")
}
}
class C {
constructor(public id: string){}
}
reusable.component.html looks like this:
<input [(ngModel)]="data[propName]">
reusable.component.ts looks like this:
@Component({
selector: "app-reusable[data][nestedProperty]",
templateUrl: "./reusable.component.html"
})
export class ReusableComponent<T> {
@Input()
nestedProperty!: string
@Input()
data!: T
}
and app.component.html as follows:
<app-reusable [data]="d1" [nestedProperty]="s1"></app-reusable>
<app-reusable [data]="d2" [nestedProperty]="s2"></app-reusable>
and app.component.ts like so:
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
d1 = new A()
d2 = new B()
s1 = "p1.id";
s2 = "p2.id";
}
The original idea was for d1.p1
to have the same value as d1["p1"]
, but it was discovered that d1["p1.id"]
does not yield the same result as d1.p1.id
.
Is there any workaround to retrieve a nested object value solely using a string path to the nested object?
One solution involved creating the property d1["p1.id"]
within the constructor and assigning it the d1.p1.id
value like this:
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
d1 = new A()
d2 = new B()
s1 = "p1.id";
s2 = "p2.id";
constructor() {
this.d1[s1] = this.d1.p1.id
this.d2[s2] = this.d2.p2.id
}
}