Sergej
Sergej

Reputation: 2196

Assign @Input() object properties to the component

I am having an Angular component with a single @Input element:

@Input('member') member: Member;

the Member interface looks like this:

export interface Member {
  name: string;
  surname: string;
  display_name: string;
  positions: number[];
  image_url: string;
  email: string;
  address: string;
  office_phone: string;
  phone: string;
  whatsapp: string;
  skype: string;
}

I want to access the member fields from html template like {{ name }}, {{ email }} etc... wtihout prefixing each of them.

For example, I do not want to access these properties like {{ member.name }}, {{ member.email }}, I like the shortcut version.

The component will have only a single @Inpurt property - the Member object.

Is there a nice way to reassign the member. properties to the Angular component? Or any other way to use a shortcut, I mensioned above?

Upvotes: 1

Views: 1181

Answers (1)

user4676340
user4676340

Reputation:

Not a good practice, but you should spread that object into your component :

ngOnInit() {
  Object.entries(this.member).forEach(([key, value]) => this[key] = value);
  // OR
  Object.assign(this, this.member);
}

You can now use them as if they were class properties. Be warned that it will override any other property with the same name on your class, so you should be careful about that solution and instead use member.XXX.

Upvotes: 4

Related Questions