Angular 角度-如何使用继承创建真正的父组件?
我需要创建一个父组件,它封装了一些ui逻辑(在component.ts中)以及一些子组件的模板逻辑(component.html) 对于模板继承,我们使用ng内容,htmls如下所示:Angular 角度-如何使用继承创建真正的父组件?,angular,Angular,我需要创建一个父组件,它封装了一些ui逻辑(在component.ts中)以及一些子组件的模板逻辑(component.html) 对于模板继承,我们使用ng内容,htmls如下所示: export class ChildComponent extends ParentComponent app.component.html: <parent [parentsInput]='X'> <child1></child1> </parent>
export class ChildComponent extends ParentComponent
app.component.html:
<parent [parentsInput]='X'>
<child1></child1>
</parent>
<parent [parentsInput]='Y'>
<child2></child2>
</parent>
<parent [parentsInput]='Z'>
<child3></child3>
</parent>
所以,我现在看到的是:html呈现正确,所以我在浏览器中确实看到子模板包含在父模板中的正确位置
但问题是:子组件无法访问父组件的属性(即parentsInput)。在Webstorm中,它实际上看起来不错,您单击子组件中的属性名称,然后导航到实际定义属性的父组件。但它在浏览器中不起作用我们如何实现这一点,以便子组件可以使用父属性作为自己的属性?
PS:我发现我们可以将父组件作为依赖项注入(比如构造函数中的@inject(ParentComponent)parent:ParentComponent)并访问属性,但这不是我想要的,因为我们的子组件可能会读取和修改许多属性,我不想单独读取所有属性。我希望有一个“继承”。我认为您的注入方法是正确的,但您可能应该使用一些javascript…spread magic,如果您打算操纵大量值,可以让生活更轻松: 如果要设置值,可以按照myChildComponentValue={…parentComponent}的思路进行操作(假设您希望它们有所不同,但我假设您希望它们与父组件保持同步) 这是我策划的一场闪电战 使用@inject将实例与spread操作符结合使用非常强大。如果您想在更大的上下文中让事情变得不那么冗长,那么您可以修改一系列属性,并将它们推送到一个进行更新的方法,然后在init上设置数组
希望这对我们有所帮助,让我们保持联系 这并不像看上去那么简单。据我所知,没有办法实现你想要的 如果我理解正确,那么您可能希望访问
子组件中的父实例,而不使用@Inject(ParentComponent)
由于您使用的是ng content
或content项目概念,我可以想到以下方法:
Parent.component.ts
export class ParentComponent {
@ContentChild (ChildComponent) child: ChildComponent; // access child in parent using ContentChild
@Input() parentsInput;
ngAfterContentInit(){
this.child.accessParent(this); // calling child function and passing parent's `this` context
}
}
export class ChildComponent{
parentInstance: ParentComponent;
// This is the main area or magical area
accessParent(instance:any){
this.parentInstance = instance;
}
}
子组件.ts
export class ParentComponent {
@ContentChild (ChildComponent) child: ChildComponent; // access child in parent using ContentChild
@Input() parentsInput;
ngAfterContentInit(){
this.child.accessParent(this); // calling child function and passing parent's `this` context
}
}
export class ChildComponent{
parentInstance: ParentComponent;
// This is the main area or magical area
accessParent(instance:any){
this.parentInstance = instance;
}
}
child.component.html
{{parentInstance.parentsInput}}
这样,您就可以在子组件中访问父组件的上下文。现在,您可以访问子组件中父组件的所有对象或属性
在演示中,我只使用了child
组件,但您当然可以使用child1
,child2
等等
我希望这会有所帮助。谢谢。您认为这比我第一次使用“@Inject(ParentComponent)”更好吗?我不想使用依赖关系的真正原因是,我努力分别读取/写入值,而不是将它们放在同一个上下文中。但是在你的方法中,我不是有同样的问题吗?顺便说一句,我不需要从父级访问子属性,这只是从子级到父级的一种方式。因此,我认为使用构造函数(public parent:ParentComponent)的方法可以得到相同的最终结果,代码更少。这两种方法都是有效的方案。通过@Inject
,您正在将父对象强制注入子对象以读取它(使用DI依赖项注入)。我的方法也很优雅地做到了这一点(没有DI,使用contentChild API)。你只需要检查哪一个对你的场景来说是平滑和方便的。祝你好运