简体   繁体   English

Angular 7,枚举和输入属性绑定

[英]Angular 7, Enum and Input property binding

The issue is when binding an enum with a view template using @Input , the enum is being resolved to undefined . 问题是使用@Input将枚举与视图模板@Input ,枚举被解析为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

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. 您正在尝试发送modes.Insert 。在父html中从父组件modes.Insert子组件,我们只能访问父html中的父公共属性,而不能访问子属性。 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. 因此,您应该首先在父组件中定义它,并在html中使用它,然后将已定义的数据从父组件发送到子组件。

in parent not in child: 在父母而不在孩子中:

public modes = FormAction;

Declare a component property type to FormAction doesn't set the property value still the property value is undefined just inlinze the mode propert 将组件属性类型声明为FormAction仍不会设置属性值,但仍未undefined属性值,只需插入模式属性即可

AppComponent 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 或者您可以使用get属性来访问FormAction枚举

AppComponent 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 必须在AppComponent中声明“ modes”属性,而不是在MemberEditor Component中声明,例如在我的appComponent模板示例中,您可以访问AppComponent的所有属性,就像您在AppComponent的范围或上下文中一样访问MemberEditor组件中的属性

But it's possible if you create a template variable ( Not RECOMMENDED ) 🙄🙄 但是有可能创建模板变量( 不推荐 )🙄🙄

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

demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM