在我的子组件中,单击按钮会触发一个过程并返回一个布尔值。我需要在父组件中捕获此布尔值并启用/禁用按钮。我以前从未使用过@Output()
。我创建了一个样本来显示问题。在开发工具中,出现此错误:
ERROR TypeError: _co.onclickValidateAndSave is not a function
child.component.ts
import { Component, OnInit, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {
//passing value to parent component thru event payload
bSuccess: boolean = false;
@Output()
public clickValidateAndSave: EventEmitter<boolean> = new EventEmitter<boolean>();
constructor() { }
ngOnInit() {
}
public onclickValidateAndSave() {
this.clickValidateAndSave.emit(this.bSuccess);
//not being logged
console.log(this.bSuccess);
}
toggleSuccess() {
this.bSuccess = !this.bSuccess;
}
}
这是child.component.html:
<div>
<div class="form-group">
<button class="btn btn-default"
(click)="toggleSuccess()">
Toggle Success
</button>
</div>
</div>
parent.component.ts:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss']
})
export class ParentComponent implements OnInit {
disableBtn: boolean = false;
constructor() { }
ngOnInit() {
}
handleClickOnChild(bSuccess) {
this.disableBtn = !bSuccess
}
}
和parent.component.html
<app-child (clickValidateAndSave)="handleClickOnChild($event)"></app-child>
<div class="row col-mg-6">
<button type="submit" class="btn btn-primary" [disabled]="disableBtn" ngDefaultControl name="name">
Submit for Approval
</button>
</div>
答案 0 :(得分:1)
尝试
<app-child (clickValidateAndSave)="handleClickOnChild($event)" ></app-child>
<div class="row col-mg-6">
<button type="submit" class="btn btn-primary" [disabled]="disableBtn"
[(ngModel)]="clickValidateAndSave">
Submit for Approval {{clickValidateAndSave}}
</button>
</div>
和父级js
disableBtn = false;
...
handleClickOnChild(bSuccess) {
this.disableBtn = !bSuccess
}
我从头开始编写代码,因此可能会有一些错误
答案 1 :(得分:1)
您将所有内容混合在一起,需要在子组件的emit(value)
字段上使用@Output
方法,并且该值将传递到您在特定组件上订阅的父组件的方法中Output
个孩子。例如看一下on this example(在“ example”文件夹中看):
在这里我们触发子组件中的事件:
toggleSuccess() {
this.clickValidateAndSave.emit(this.bSuccess = !this.bSuccess);
}
我们在父组件中订阅该事件:
<app-child (clickValidateAndSave)="onClickValidateAndSave($event)"></app-child>
这里是我们在子事件上订阅的父方法:
onClickValidateAndSave(value: boolean) {
this.buttonDisabled = value;
}
请注意,我们可以通过参数访问Output
事件值。
希望有帮助。