Angular-如何使用继承创建真正的父组件



我需要创建一个父组件,它封装了一些ui逻辑(在component.ts中(

以及一些子组件的一些模板逻辑对于模板继承,我们使用ng内容,html如下所示:

app.component.html:

<parent [parentsInput]='X'>
<child1></child1>
</parent>
<parent [parentsInput]='Y'>
<child2></child2>
</parent>
<parent [parentsInput]='Z'>
<child3></child3>
</parent>

parent.com.ponent.html

<div>
... {{parentsInput}}
</div>
<ng-content></ng-content>   <!-- dynamic content where child templates are injected -->
<div>
... {{parentsInput}}
</div>

child.component.html

<div>
... {{parentsInput}}
</div>

并且我还将parentComponent定义为";"父";像这样的孩子:

export class ChildComponent extends ParentComponent

所以,我现在拥有的是:html被正确渲染,所以我在浏览器中确实看到子模板包含在父模板中的正确位置。

但问题是:子组件无法访问父组件的属性(即parentsInput(。在Webstorm中,它实际上看起来不错,您可以单击子组件中的属性名称,然后导航到实际定义属性的父组件。但不知何故,它在浏览器中不起作用我们如何实现这一点,以便子组件可以将父属性用作自己的属性

附言:我已经发现,我们可以将父组件作为依赖项注入(比如构造函数中的@inject(ParentComponent(parent:ParentComponent等(并访问属性,但这不是我想要的,因为我们的子组件可能会读取&修改许多属性,我不想单独读取所有属性。我想要一个";"继承";。

这并不像看上去那么简单。(据我所知(你不可能实现你想要的东西。

如果我理解正确,那么您可能希望在不使用@Inject(ParentComponent)的情况下访问child component中的parent instance

由于您使用的是ng-content或内容项目概念,我可以想到以下方式,

父组件.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
}

}

子组件.ts

export class ChildComponent{
parentInstance: ParentComponent;
// This is the main area or magical area
accessParent(instance:any){
this.parentInstance = instance;
}

}

child.component.html

{{parentInstance.parentsInput}}

演示


通过这种方式,您将能够访问子组件中父组件的上下文。现在,您可以访问子组件中父组件的所有对象或属性。

在DEMO中,我只使用child组件,但您当然可以使用child1child2&等等。

我希望这会有所帮助。

我认为您在注入方面走在了正确的轨道上,但您可能应该使用一些javascript。。。如果你打算操纵很多价值观,传播魔法让生活更轻松:

如果你想设置这些值,你可以按照myChildComponentValue={…parentComponent}的思路来做一些事情(假设你希望它们有所不同,但我认为你希望它们与父组件保持最新(。

这是我做的一个堆叠https://stackblitz.com/edit/angular-ivy-42q7yq使用@inject将实例与spread操作符结合使用是非常强大的。如果你想在更大的上下文中让事情变得不那么冗长,你可以有一个属性的appay,你可以修改这些属性,并将其推送到一个进行更新的方法,并将数组设置为init。

希望这能帮助到一些人,请随时关注我们!

最新更新