[英]Angular 7, Enum and Input property binding
問題是使用@Input
將枚舉與視圖模板@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
您正在嘗試發送modes.Insert
。在父html中從父組件modes.Insert
子組件,我們只能訪問父html中的父公共屬性,而不能訪問子屬性。 因此,您應該首先在父組件中定義它,並在html中使用它,然后將已定義的數據從父組件發送到子組件。
在父母而不在孩子中:
public modes = FormAction;
將組件屬性類型聲明為FormAction
仍不會設置屬性值,但仍未undefined
屬性值,只需插入模式屬性即可
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>
必須在AppComponent中聲明“ modes”屬性,而不是在MemberEditor Component中聲明,例如在我的appComponent模板示例中,您可以訪問AppComponent的所有屬性,就像您在AppComponent的范圍或上下文中一樣訪問MemberEditor組件中的屬性
但是有可能創建模板變量( 不推薦 )🙄🙄
<app-member-editor [mode]="mEditor.modes.Insert" #mEditor></app-member-editor>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.