我有2个组件:AppComponent和ChildComponent。 ChildComponent是AppComponent的子组件。 如何将更改的“variable1”从ChildComponent发送回AppComponent?
AppComponent [html]:
int
AppComponent [ts]:
@RequestMapping(value = "/excelDataView", method=RequestMethod.GET )
public ModelAndView getExcel(final HttpServletRequest request, final HttpServletResponse response){
log.info("Inside getExcel()");
List<DataValidationResults> dataValidationResults = new ArrayList<DataValidationResults>();
dataValidationResults = dataValidationDelegate.exportData(TaskId);
log.info("dataValidationDelegate.exportData(TaskId) value " + dataValidationDelegate.exportData(TaskId));
request.setAttribute("dataValidationResults", dataValidationResults);
return new ModelAndView(new ExcelDataView(), "dataValidationResultsModel", dataValidationResults);
}
ChildComponent [ts]:
<child [variable1]="variable1">PARENT</child>
答案 0 :(得分:1)
您可以使用EventEmitter
和@Output
执行此操作,并在子标记中标记双向绑定。所以你的子标签添加了双向绑定:
<child [(variable1)]="variable1">PARENT</child>
你孩子的用变量名标记这个事件发射器,后缀Change
(对于双向绑定起作用很重要!)
@Input() variable1: string;
@Output() variable1Change = new EventEmitter<string>()
并且每当您想要将变量更改传递给父项时,在子项中执行:
this.variable1Change.emit('my new value')
作为旁注,请注意我已根据文档样式指南从@Input
删除了别名:https://angular.io/guide/styleguide#avoid-aliasing-inputs-and-outputs
答案 1 :(得分:0)
我可能会迟到一点,但更容易:使用viewChildren:
父组件TS:
@ViewChild('child') child: ChildComponent;
// ...
this.myVariable = this.child.variable1;
父组件HTML:
<child #child>PARENT</child>
子组件TS:
variable1 = '';
// ...
this.variable1 = 'Hello world';
答案 2 :(得分:0)
下面的示例包含父级到子级的交互以及子级到父级的交互。 you can also try here
app.component.ts - 父组件
synchronized
app.component.html - 父组件的HTML
import { Component, Output,EventEmitter } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
//passing values from parent to child
master = "child";
//Getting value from child
childToParent(name){
this.master=name;
}
}
app-child.component.ts - 子组件
<div>
<span>Master to Child </span><input type="textbox" [(ngModel)]='master'>
</div>
<app-child [master]=master (childToParent)="childToParent($event)"></app-child>