我是 Angular 2 的新手,所以请宽容一点。
我想在子组件中使用函数(在父组件中声明)。我正在使用@output。这个函数应该返回一些字符串,子进程需要将该字符串发送到api。
所以我有一些父函数:
public ToJsonDate = (value: string) =>{
try {
let parts = value.split('-').map(Number);
parts[1] -= 1;
let date = new Date(Date.UTC.apply(null, parts));
let textContent = '/Date(' + date.getTime() + '' + this.invoiceDataParent['temp'].Zone + ')/';
console.log('test1', textContent);
return textContent;
} catch(error){
console.log(error);
}
}
在 HTML 中我有:
div class="column2"><invoice [invoiceDataREST]='invoiceDataParent' (jsonDate)="ToJsonDate($event)"></invoice></div>
在子组件上我使用输出机制:
@Output() jsonDate: EventEmitter<string> = new EventEmitter<string>();
我想要做的是在子进程的另一个函数中执行这个函数:
private sendInvoiceRequest() {
this.isEdit = false;
this.invoiceDataREST['ResponseDetails'].DocumentDate = this.jsonDate.emit(this.invoiceForm.controls['docDate'].value);
console.log('test2',this.jsonDate.emit(this.invoiceForm.controls['docDate'].value);}
现在: 控制台中的 test1 显示了良好的输出 - 因此该函数肯定会执行,但控制台中的 test 2 显示“未定义”
有人可以解释一下我做错了什么吗?我错过了什么吗?
最佳答案
Output
属性不是双向的。他们发送数据,期间。没有通过输出事件发射器接收输入。您需要做的是创建一个 Input
属性,并让父函数将更新后的值分配给子组件。例如:
<div class="column2"><invoice [invoiceDataREST]='invoiceDataParent' (jsonDate)="ToJsonDate($event)"></invoice></div>
export class Parent{
public ToJsonDate = (value: string) =>{
try {
let parts = value.split('-').map(Number);
parts[1] -= 1;
let date = new Date(Date.UTC.apply(null, parts));
let textContent = '/Date(' + date.getTime() + '' + this.invoiceDataParent['temp'].Zone + ')/';
console.log('test1', textContent);
//assign new value to property that goes back into child component
this.invoiceDataParent['ResponseDetails'].DocumentDate = textContent;
} catch(error){
console.log(error);
}
}
}
export class Child{
@Input() invoiceDataREST: any;
@Output() jsonDate: EventEmitter<string> = new EventEmitter<string>();
private sendInvoiceRequest() {
this.isEdit = false;
this.jsonDate.emit(this.invoiceForm.controls['docDate'].value);
}
}
我尝试更新您的代码以展示它应该如何工作。 emit
不会从父级检索值。它只是将一个值out发送给父级。然后,父级会将值分配给发送给子级的对象的正确属性。
希望这有帮助。
关于javascript - 父函数在子组件中返回未定义 - angular2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43610704/