首页 文章

如何从Angular2中的父组件中的组件列表中调用子组件中的方法?

提问于
浏览
0

我有子组件,它基本上是一个列表组件,在父组件的模板中迭代 . 我想调用一个方法驻留在父组件的子组件中 . 我想调用该方法属于众多组件之一 .

例如,这是我的子组件:

@Component({
    selector: 'list-item',
    template: '<li>{{value}}</li>',
})
export class ListItem implements OnInit {
    @Input value: number;

    changeValue(newValue) {
      this.value = newValue;
    }
}

这就是我的父组件的样子 -

@Component({
    selector: 'list',
    template: '<div><list-item *ngFor="let item of items" [value]="item.value"></list-item></div>',
})
export class List implements OnInit {
    // Some code to call **changeValue** 
    // method of the let's say the second 
    // list-item from the template
}

我知道 @ViewChild 装饰器,但它似乎只适用于第一个 .

将子组件视为独立的可重用组件 . 因此使用pub / sub并不是一个好主意 .

1 回答

  • 0

    我同意上面的评论,但是如果你需要......由于组件是一个类,你应该能够访问它的 public 方法 . 您需要在父级 providers: [ChildComponent] 中提供子级 .

    @Component({
          selector: 'parent',
          templateUrl: './parent.component.html',
          styleUrls: ['./parent.component.scss'],
          providers: [ChildComponent]
        })
        export class ParentComponent implements OnInit {
    
        constructor(private child: ChildComponent){}
    
        ngOnInit() {
          this.child.foo();
        }
    
    }
    
     @Component({
          selector: 'child',
          templateUrl: './child.component.html',
          styleUrls: ['./child.component.scss'],
    
        })
        export class ChildComponent implements OnInit {
    
        constructor(){}
    
      public foo() {
        console.log('FOO')
      }
    
    }
    

相关问题