Angular 7+,从父级调用子级组件的方法好吗?

时间:2019-07-17 06:45:28

标签: angular angular7

有时我想从父组件调用子组件的方法,或者以某种方式通知子组件(从父组件)调用某些东西。

第一个(从父级调用子级组件的方法):

// CHILD
@Component({
  selector: 'child-component',
  template: '<p>child</p>'
})

class ChildComponent {

  doSomething() {
    console.log('I am from child')
  }

}

// PARENT
@Component({
  selector: 'parent-component',
  template: '<child-component></child-component>',
})

class ParentComponent{

  @ViewChild(ChildComponent ) child: ChildComponent;

  ngAfterViewInit() {
    this.child.doSomething();
  }
}

第二(通知子组件打电话)

//CHILD
export class ChildComponent implements OnInit {

  @Input() notify: Subject<boolean>;

  ngOnInit(){
     this.notify.subscribe(v => { 
        console.log("I am from child");
     });
  }

}

//PARENT
export class ParentComp {

    notify: Subject<boolean> = new Subject();

    notifyChild(){
        this.notify.next(true);
    }

}

这是我的问题:

1)第一种方法的优缺点是什么?另外,如果您正在从父级调用子级的方法,这是否意味着您的组件架构不好,还是需要修复其他问题?

2)第二种方法的优缺点是什么?

3)避开它们好吗?

我正拼命寻找这些问题的答案(有解释),如果有人可以提供答案,那将是很好的。

3 个答案:

答案 0 :(得分:2)

如果可能,我会避免使用任何一种方法。如果您发现自己需要做很多事情,那么您可能没有适当地在父母和孩子之间分担责任。您应该将所有必要的数据传递给孩子,以便它知道何时调用任何函数,如果仍然不调用,则可能不是组件责任。话虽如此,如果您发现自己编写了一个非常复杂的应用程序并且仍然需要很多此功能,那么我将使用ngrx之类的东西来正确管理状态。另外,如果要使用第二种方法,则应将主题分为服务。至于推理,随着应用程序规模和复杂性的增长,依靠可预测的信息和动作流非常方便,这就是为什么ngrx很有用,但是在您的应用程序中多次执行第一种或第二种方法可能不会杀死您的原因你。

答案 1 :(得分:1)

您可以使用changedetection:

// CHILD
@Component({
  selector: 'child-component',
  template: '<p>child</p>',
  changeDetection: ChangeDetectionStrategy.OnPush
})

class ChildComponent implements onChanges{
  @Input() status: boolean;
  doSomething() {
    console.log('I am from child')
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes.status) {
        this.doSomething();
    }
  }

}

// PARENT
@Component({
  selector: 'parent-component',
  template: '<child-component [status]="status"></child-component>',
})

class ParentComponent{

  status: boolean;

  ngAfterViewInit() {
    this.status = true;
  }
}

答案 2 :(得分:1)

两个实现都违反关注点分离的原则。子组件不应该负责为父组件计算内容,因为这意味着如果没有子组件,父组件可能无法工作。 如果不同组件需要一个函数或某些计算值,则应将它们放在公共服务中,以将其注入两个组件中。

相关问题