Angular7、Enum与Input属性绑定

Angular 7, Enum and Input property binding

问题是使用 @Input 将枚举与视图模板绑定时,枚举被解析为 undefined。 组件:

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);
  }
}

视图模板:

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

控制台:

Cannot read property 'Insert' of undefined

将组件 属性 类型声明为 FormAction 不设置 属性 值仍然 属性 值是 undefined 只是 inlinze 模式属性

AppComponent

  modes = FormAction.Insert;

模板

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

或者您可以使用 get 属性 访问 FormAction 枚举

AppComponent

  get modes() {
    return FormAction
  }

模板

  <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

但是如果您创建一个模板变量是可能的(不推荐

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

demo

您正在尝试将 modes.Insert 从 parent 发送到 parent html 中的 child 组件,我们只能访问 parent public 属性 在 parent html 中而不是 child 属性。所以你应该首先在 parent 组件中定义它并在它的 html 中使用它并将定义的数据从 parent 发送到 child.

在 parent 不在 child:

public modes = FormAction;