gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:25:48 24 4
gpt4 key购买 nike

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

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

// 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();
}
}

2nd(通知子组件调用):

//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) 避免它们好不好?

我正在拼命寻找这些问题的答案(附有解释),如果有人可以提供它们,那就太好了。

最佳答案

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

关于Angular 7+,从父组件调用子组件的方法好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57069988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com