1

在我的 Angular 应用程序中,我有一个名为Component1selector的组件component-1,它的模板包含一个自身的嵌套实例:

<div> <component-1></component-1> </div>

所以parent Component1包含一个child Component1

我的目标:

Component1包含一个方法method1()。我想method1从父组件调用子组件。类似的东西this.child.method1()

我试过的:

在组件中,我child使用以下代码:@ViewChild(Component1) child: Component1;. 如果我这样做,console.log(this.child)我会得到一个对象,其中包含来自 的所有@Input@OutputComponent1,但不包含method1().

我想知道的:

我如何访问this.child.method1()

4

3 回答 3

1

我建议不要尝试在父级中调用子级方法。考虑重新考虑应用程序的架构和数据流。您可能希望反过来,使用事件发射器从子级调用父级中的方法以进行通信https://angular.io/guide/component-interaction#parent-listens-for-child-event

父组件:

export class ParentComponent implements OnInit {
    .....
    onExecute() {
        // Execute some code
    }
}

子组件

@Component({
   selector: 'child-component',
   templateUrl: './child-component.component.html',
   styleUrls: ['./child-component.component.scss']
})
export class ChildComponent implements OnInit {
    @Output() execute = new EventEmitter();
    .....
    someMethod() {
        this.execute.emit(); // you can send any variable to parent
    }
}

this.execute.emit();被触发时,您的父元素 ( onExecute) 中的处理程序将被调用。

这是一个stackblitz演示

于 2019-12-12T23:54:55.947 回答
0

您是否尝试过在子组件中使用公共方法。

export class HelloComponent  {

  @Input() name: string;
  public method1() {
    console.log('yes It iss called');
  }

}

https://stackblitz.com/edit/angular-i55bbe

于 2019-12-13T00:03:27.450 回答
0

我真的不明白你为什么要这样做。通常有必要从子调用父方法,例如关闭模式等。但请查看此链接https://stackoverflow.com/a/38974968/7393630。它可能有助于您想做的事情。

于 2019-12-12T23:50:52.333 回答