当用户单击父组件中存在的提交按钮时,我需要将输入的值从子组件传递到父组件。
childComp 模板
<input
type="password"
[(ngModel)]="userPasswordForm.inputId"
class="mr-password-field k-textbox"
/>
childComp TS 文件
export class PasswordInputComponent{
constructor() { }
@Output() inputValue = new EventEmitter<string>();
userPasswordForm:any={'input':''};
emitValue(value: string) {
this.inputValue.emit(value);
}
}
父组件模板
<child-component (inputValue)="" > </child-component>
<button (click)="getValueFromChild()"> </button>
父组件 TS 文件
tempUserFormPasswords:any=[];
.
.
.
getValueFromChild(receivedVal){
this.tempUserFormPasswords.push(receivedVal);
}
如果按钮存在于子组件中,则很容易执行此操作。但在这种情况下,应该在单击父组件中的按钮时传递该值!
最佳答案
对于单个子组件: 使用ViewChild
对于多个 ChildComponent 使用:ViewChildren
父组件 TS 文件
单个子组件:
tempUserFormPasswords:any=[];
@ViewChild(ChildComponent) child: ChildComponent;
.
.
.
getValueFromChild(receivedVal){
var data = child.getData();
this.tempUserFormPasswords.push(data);
}
多个子组件:
tempUserFormPasswords:any=[];
@ViewChildren(ChildComponent) child: ChildComponent;
@ViewChildren(ChildComponent) children: QueryList<ChildComponent>;
.
.
.
getValueFromChild(receivedVal){
let data;
children.forEach(child => (data = this.updateData(child.data));
this.tempUserFormPasswords.push(data);
}
关于javascript - 当父组件上单击按钮时,如何将数据从子组件传递到父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65923104/