简体   繁体   English

角度 | 父组件作为输入传递给子组件

[英]Angular | Parent component being passed as input to child

I recently started working on an Angular project and noticed a practice that I thought was a bit odd.我最近开始从事 Angular 项目并注意到一种我认为有点奇怪的做法。 In this case, the connection between a parent and child component was being made by passing the parent component itself as input to the child.在这种情况下,父组件和子组件之间的连接是通过将父组件本身作为输入传递给子组件来建立的。

Parent Class Component父类组件

@Component({
    selector: 'app-parent',
    templateUrl: './parent.component.html',
    styleUrls: ['./parent.component.css']
})
export class ParentComponent {
    ...
}

Parent Template Component父模板组件

<div>
    <app-child [parent]="this"></app-child>
</div>

Child Class Component子类组件

@Component({
    selector: 'app-child',
    templateUrl: './child .component.html',
    styleUrls: ['./child .component.css']
})
export class ChildComponent {
    @Input() parent: ParentComponent;
}

Just wanted to know if this is common or is it bad practice?只是想知道这是常见的还是不好的做法? Well I found it very strange嗯,我觉得很奇怪

Never seen this practice before, although I took part in the development in a lot of projects.以前从未见过这种做法,虽然我参与了很多项目的开发。 I see there only two reasons we might need this, it's when we don't know what the parent component might be, or wanna get it's context.我认为我们可能需要这个的原因只有两个,当我们不知道父组件可能是什么,或者想获得它的上下文时。 But we can do almost the same with this constructor .但是我们可以用这个constructor做几乎相同的事情。

constructor(@Inject(ParentComponent) private parent: ParentComponent){
  ...some code
}

So, we can't say, is this good or bad.所以,我们不能说,这是好事还是坏事。 It depends on what approach your team uses.这取决于您的团队使用的方法。 However, it would be nice to work on architecture of application, if it came to this.但是,如果涉及到这一点,那么在应用程序架构上工作会很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 数据未从子组件 angular 8 传递给父组件 - Data not being passed to parent from child component angular 8 输入值未传递到子组件angular5吗? - Input value is not passed to child component angular5? Angular 异步传递的输入数据 pipe 在子组件中是 null 尽管不是 Z37A6259CC0C1DAE299A78066 中的 Z37A6259CC0C1DAE299A78066 - Angular input data passed by async pipe is null in child component although is not null in parent Angular 2单元测试数据从父组件传递到子组件 - Angular 2 unit testing data passed from parent component to child component Angular:@Input 更改未在子组件中触发 - Angular: @Input change not being fired in child component 从 Angular 父组件传递给子组件的数据在子组件中未定义 - Data passed from an Angular parent component to a child component is undefined in child component 如何在Angular 2中访问从父组件传递的输入数据 - How to access Input data passed from parent component in Angular 2 在使用@input() 传递数据之前加载 Angular 2 子组件 - Angular 2 child component loads before data passed with @input() 子组件中的Angular @Input也会更新父组件中的值 - Angular @Input in child component also updates value in parent component Angular4 @Input()将值从父组件传递到子组件 - Angular4 @Input() to pass value from parent component to child component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM