我创建了一个子组件,它有一个我想要调用的方法 .
当我调用这个方法时它只触发 console.log()
行,它不会设置 test
属性??
以下是我的更改快速启动Angular应用程序 .
家长
import { Component } from '@angular/core';
import { NotifyComponent } from './notify.component';
@Component({
selector: 'my-app',
template:
`
<button (click)="submit()">Call Child Component Method</button>
`
})
export class AppComponent {
private notify: NotifyComponent;
constructor() {
this.notify = new NotifyComponent();
}
submit(): void {
// execute child component method
notify.callMethod();
}
}
孩子
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'notify',
template: '<h3>Notify {{test}}</h3>'
})
export class NotifyComponent implements OnInit {
test:string;
constructor() { }
ngOnInit() { }
callMethod(): void {
console.log('successfully executed.');
this.test = 'Me';
}
}
如何设置 test
属性?
3 回答
您可以使用
@ViewChild
获取更多信息来检查此link这对我有用!对于Angular 2,在父组件中调用子组件方法
Parent.component.ts
Child.component.ts
我认为最简单的方法是使用Subject . 在下面的示例代码中,每次调用'tellChild'时都会通知子项 .
Parent.component.ts
Parent.component.html
Child.component.ts