[英]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.