[英]Angular 4: why can't I call a public function in my ngOnInit()?
So I've got the following code in my ngOnInit(): 因此,我的ngOnInit()中包含以下代码:
ngOnInit() {
$('#inputForm').submit(function(e) {
e.preventDefault();
this.uploadFormData();
});
$('#fileUpload').on('change', function() {
const fileString = $('#fileUpload').val();
const fileType = $('#fileUpload').prop('files')[0].type;
if (fileType !== 'text/xml') {
$('#message').html('File to upload must be an XML file!!!');
if (!$('#message').hasClass('error')) {
$('#message').addClass('error');
}
} else {
$('#message').html('File to upload is an XML file!!!');
if ($('#message').hasClass('error')) {
$('#message').removeClass('error');
}
$('#message').addClass('correctFile');
}
});
} }
This will watch for the onchange event & when I submit my form. 当我提交表单时,它将监视onchange事件。 When I submit my form, I want to call a public function that's outside of this ngOnInit(), and it looks like this:
提交表单时,我想调用此ngOnInit()之外的公共函数,它看起来像这样:
public uploadFormdata(): void {
const form = $('#inputForm').val();
const files = ($('#fileUpload') as any).files;
const formData = new FormData();
const file = files[0];
formData.append('tenant', form[0]);
formData.append('title', form[1]);
formData.append('file', file, file.name);
this.uploadService.uploadForm(formData)
.subscribe(res => this.fileUploaded(res));
}
Why won't "this.uploadFormData()" in my ngOnInit() work? 为什么我的ngOnInit()中的“ this.uploadFormData()”不起作用? It says "property 'uploadFormData' does not exist on type 'HTMLElement'".
它说“类型'HTMLElement'上不存在属性'uploadFormData'”。
Use the arrow function, so that this
refers to your component's class. 使用箭头功能,使
this
指的是组件的类。 If you don't, this will refer to the DOM element on which you bound the event, ie the inputForm
field 如果没有,它将引用绑定事件的DOM元素,即
inputForm
字段
$('#inputForm').submit(e => {
e.preventDefault();
this.uploadFormData();
});
Note : you should really avoid using jQuery for manipulating the DOM, as angular is not aware of changes caused by jQuery. 注意 :您应该避免使用jQuery来操作DOM,因为angular并没有意识到jQuery会导致更改。
Because, this
context into your sumbit form refered the $('#inputForm')
not the class of your component. 因为,
this
上下文在您的sumbit表单中$('#inputForm')
了$('#inputForm')
而不是组件的类。 In your situation, you have to save your context this
into variable 在你的情况,你必须保存上下文
this
为变量
ngOnInit() {
const $this = this;
$('#inputForm').submit(function(e) {
e.preventDefault();
$this.uploadFormData();
});
// ...
}
Or you should use arrow function: 或者您应该使用箭头功能:
ngOnInit() {
$('#inputForm').submit((e) => {
e.preventDefault();
this.uploadFormData();
});
// ...
}
View elements only load after " OnInit ", you can use AfterViewInit
视图元素仅在“ OnInit”之后加载,您可以使用AfterViewInit
ngAfterViewInit() { $('#inputForm').submit(function(e) { e.preventDefault(); this.uploadFormData(); }); }
Use Element ref instead of ordinary JavaScript/ jQuery selector
使用Element ref代替普通的JavaScript / jQuery选择器
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.