Reputation:
I am trying to define a model
in angular and use it html.
Here is my code:
'user.model.ts'
export class User{
private name: string;
constructor($name: string){
this.name = $name;
}
public get $name(): string {
return this.name;
}
public set $subject(value: string) {
this.name = value;
}
}
component.ts
myUsers: Array<User>;
ngOnInit(){
//api call
this.myUsers= resultFromAPi;
}
component.html
<div *ngFor="let user of myUsers">
{{user.name}}
</div>
Now, although in the UI, I can see the name and it works perfectly. But at the same time in my code editor(VS code), I am seeing an error:
[Angular] Identifier 'name' refers to a private member of 'User'
I know I can fix the error by making the fields public, but I think that would be bad design.
Update
{{user.$name}}
does not even show the name on UI
Upvotes: 0
Views: 1495
Reputation: 62238
So why is your template code include {{user.name}}
when you defined a public getter named $name
?
{{user.name}}
should be
{{user.$name}}
Or change your User
class member names. The other code that does not make sense to me is calling your setter $subject
. This would confuse me if I inherited your code or had to do something in the template after you created it. Use intuitive and consistent names for your fields and access properties.
Personally I would have just had a public field name
or a private field $name
with public getter name
.
Seems you have issues in code you have not shown, based purely on trend for this type of question I recommend you just create an interface based on the incoming json
and return that from your service.
import { HttpClient } from '@angular/common/http';
export interface IUser {
name: string;
}
export class UserService {
constructor(private httpService: HttpClient) {}
getUsers(): Observable<IUser[]> {
return this.httpService.get<IUser[]>('your user end point here');
}
}
Upvotes: 1
Reputation: 41447
When we are using AOT (ahead of time) compiler, all the template members such as properties and method must be define in public. you can't access private properties in your templates if you want to use ahead-of-time compilation.
Upvotes: 0