1

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

there will be no other properties, because the object is only for the member object preview. But the @Input() object may change, so it should be reassigned in ngOnChanges(). I thought there is a better way for this.
Well replace OnInit with OnChanges ! And no, there's no better way, unless creating all the properties by hand but that's all : in the template, you only have access to class members, so you have to either use the member property, or create a new property for evey key of member.
@Sergej but you do have several ways of doing so, like decorators, directives and so on. But the easiest and cleanest one still is this one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.