Angular 7, Enum and Input property binding

6.3k views Asked by At

The issue is when binding an enum with a view template using @Input, the enum is being resolved to undefined. The component:

enum FormAction {
  Insert,
  Update
}    
@Component({
  selector: 'app-member-editor',
})
export class MemberEditorComponent implements OnInit {
  modes = FormAction;

  @Input('mode') mode: FormAction;

  ngOnInit() {
    console.log(this.mode);
  }
}

The view template:

<app-member-editor [mode]="modes.Insert"></app-member-editor>

The console:

Cannot read property 'Insert' of undefined
2

There are 2 answers

0
Fatemeh Fazli On BEST ANSWER

you are trying to send modes.Insert from parent to child component in parent html, and we just can access the parent public property in parent html not the child properties. so you should first define it in parent component and use it in it's html and send the defined data from parent to child.

in parent not in child:

public modes = FormAction;
0
Muhammed Albarmavi On

Declare a component property type to FormAction doesn't set the property value still the property value is undefined just inlinze the mode propert

AppComponent

  modes = FormAction.Insert;

Template

 <app-member-editor [mode]="modes.Insert"></app-member-editor>

or you can use get property to access to FormAction enum

AppComponent

  get modes() {
    return FormAction
  }

Template

  <app-member-editor [mode]="modes.Insert"></app-member-editor>

modes property has to be declared in the AppComponent not in the MemberEditor Component as my example in the template of appComponent you have access to all the property of the AppComponent like you are in the scope or context of the AppComponent the way you don't have access to property in the MemberEditor Component

But it's possible if you create a template variable (Not RECOMMENDED)

<app-member-editor [mode]="mEditor.modes.Insert" #mEditor></app-member-editor>

demo