[英]Call function from parent angular
父.html
<p>parent</p>
<children></children>
父母.ts
sayhello() {
console.log("hello")
};
儿童.ts
callHellotoConsole{
this.sayhello()
}
我如何从父组件调用 sayhello() 函数! 我已经这样称呼了
<children [sayhello] = "sayhello()"></children>
儿童.ts
@Input() sayhello: Function;
我会建议不要试图在孩子中调用父方法。 考虑使用事件发射器从子https://angular.io/guide/component-interaction#parent-listens-for-child-event与父通信。
父组件:
export class ParentComponent implements OnInit {
.....
onSayHello() {
// Execute some code
}
}
父组件模板:
<p>parent</p>
<children (sayHello)="onSayHello()"></children>
子组件
@Component({
selector: 'child-component',
templateUrl: './child-component.component.html',
styleUrls: ['./child-component.component.scss']
})
export class ChildComponent implements OnInit {
@Output() sayHello = new EventEmitter();
.....
sayHello() {
this.sayHello.emit(); // you can send any variable to parent
}
}
当this.sayHello.emit();
被触发,您的父元素 (`onSayHello) 中的处理程序将被调用。
这是一个stackblitz演示
在将其作为输入值传递给子组件时,不要在 'sayHello' 中添加大括号 '()'。
像这样尝试:-
父母.ts
export class ParentComponent implements OnInit {
constructor() { }
ngOnInit() {
}
sayHello() {
console.log('Hello');
}
}
父.html
<app-child [sayHello]="sayHello"></app-child>
Child.ts
export class ChildComponent implements OnInit {
constructor() { }
@Input()
sayHello: Function;
ngOnInit() {
}
callHello() {
this.sayHello();
}
}
像这样尝试:
父母.ts
@ViewChild('childRef') child: ChildComponent;
child.sayhello()
.html
<children #childRef></children>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.