[英]Access parent component from child component when parent component using ng-content Angular
I'm trying to access parent component from child component using dependence injection.我正在尝试使用依赖注入从子组件访问父组件。 It works, I can access to parent to using its methods and properties but I have not seen this approach on Angular doc.
它有效,我可以访问父级以使用它的方法和属性,但我没有在 Angular 文档上看到这种方法。 So do you have any idea about this approach?
那么你对这种方法有什么想法吗? Should I use it?
我应该使用它吗?
Because the parent component using ng-content (like transclude angularjs) so I cannot using EventEmitter @Output approach.因为父组件使用 ng-content(比如 transclude angularjs)所以我不能使用 EventEmitter @Output 方法。
The bellow is my code:下面是我的代码:
wizard.component.ts (parent) Wizard.component.ts(父级)
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'wizard',
template: `
<div>
<ng-content></ng-content>
<button>Back</button>
<button>Next</button>
</div>
`
})
export class WizardComponent implements OnInit {
steps = [];
constructor() { }
addStep(step) {
this.steps.push(step);
}
ngOnInit() { }
}
step.component.ts (child) step.component.ts(子)
import { WizardComponent } from './wizard.component';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'step',
template: `
<div>Step <ng-content></ng-content></div>
`
})
export class StepComponent implements OnInit {
constructor(private parent: WizardComponent) {
this.parent.addStep(this);
}
ngOnInit() { }
}
app.component.html (main app) app.component.html(主应用程序)
<wizard>
<step>1</step>
<step>2</step>
<step>3</step>
</wizard>
Looking forward to hearing your opinions.期待听到您的意见。 Thanks!
谢谢!
Parent Component-> Wizard Component父组件->向导组件
@Component({
selector: 'wizard',
template: `
<div>
<steps [steps]="steps"> </steps>
<button> Back </button>
<button> Next </button>
<button (click)="addStep()"> Add a step </button>
</div>
`,
})
export class WizardComponent {
steps:any[]=new Array();
constructor() {
this.steps.push({id:1,name:'abc'});
this.steps.push({id:2,name:'abc'});
this.steps.push({id:3,name:'abc'});
}
addStep(){
let count = parseInt(this.steps.count) + 1;
this.steps.push({id:count,name:'abc'});
}
}
StepComponent -> Child component StepComponent -> 子组件
@Component({
selector: 'steps',
template: `
<div>
<span *ngFor="let step of steps">
<label> {{step.id}} </label>
<div> {{step.name}} </div>
</span>
</div>
`,
})
export class StepsComponent {
@Input() steps:any[]=new Array();
constructor() {
}
}
Update 1: Different elements will be present in each steps, so I suggest you to use the <ng-content>
as below更新1:每个步骤中都会出现不同的元素,所以我建议你使用
<ng-content>
如下
<div>
<ng-content select=".step-body"> </ng-content>
</div>
Your wizard will look like你的向导看起来像
<table>
<tr>
<td>
<steps>
<div class="step-body">
hi hello
</div>
</steps>
</td>
<td>
<steps>
<div class="step-body">
something else
</div>
</steps>
</td>
</tr>
</table>
Finally I found the document about parent dependence injection here https://angular.io/docs/ts/latest/cookbook/dependency-injection.html#!#known-parent .最后我在这里找到了关于父依赖注入的文档https://angular.io/docs/ts/latest/cookbook/dependency-injection.html#!#known-parent 。
And there is an article that using it: https://blog.thoughtram.io/angular/2015/04/09/developing-a-tabs-component-in-angular-2.html还有一篇文章使用它: https ://blog.thoughtram.io/angular/2015/04/09/developing-a-tabs-component-in-angular-2.html
Hope it will help someone who has the same concern like me.希望它能帮助像我一样有同样担忧的人。
You can provide parent and child communication by creating a property on the parent object that uses the querylist.您可以通过在使用查询列表的父对象上创建属性来提供父子通信。 You must also add a property or method on the child component to receive the parent pointer.
您还必须在子组件上添加属性或方法以接收父指针。
@ContentChildren( OptionComponent )
public Options: QueryList<OptionComponent>;
This will give you a pointer to all the children in the parent object.这将为您提供指向父对象中所有子对象的指针。 These can be projected entries (ngContent) or direct html declarations.
这些可以是投影条目 (ngContent) 或直接 html 声明。 The query list will then grab a pointer to each child for you.
然后查询列表将为您获取指向每个孩子的指针。
then in your in you parent object然后在你的父对象中
public ngAfterViewInit(): void
{
this.Options.forEach( ( item ) =>
{
item.Parent = this;
} )
}
Grossly simplified but I think this provides the basic idea.大大简化了,但我认为这提供了基本思想。
The docs for parent DI / known parent moved here:父 DI / 已知父级的文档移至此处:
https://angular.io/guide/dependency-injection-navtree#find-a-parent-component-of-known-type https://angular.io/guide/dependency-injection-navtree#find-a-parent-component-of-known-type
Another approach is to use a class interface and find the parent using this class interface另一种方法是使用类接口并使用该类接口查找父级
The class interface : It's an abstract class used as an interface rather than as a base class.类接口:它是一个抽象类,用作接口而不是基类。
Based on the definition, the parent should implement the class interface.根据定义,父类应该实现类接口。
A scenario: If we have a child class called 'AppleComponent' and we need to access it's parent class 'FruitsComponent' inside this child class to get the props/methods of this parent.一个场景:如果我们有一个名为“AppleComponent”的子类,我们需要在该子类中访问它的父类“FruitsComponent”以获取该父类的道具/方法。
1- Make the class interface 1-制作类界面
export abstract class Parent {
abstract amount: number;
}
Here we defined the class that will be implemented by the parent and it'll have an abstract property as an example that will be defined in the FruitsComponent.在这里,我们定义了将由父类实现的类,它将具有一个抽象属性作为示例,该属性将在 FruitsComponent 中定义。
2- Update the Fruits class 2-更新水果类
@Component({
...
providers: [{ provide: Parent, useExisting: forwardRef(() => FruitsComponent) }],
})
export class FruitsComponent implements Parent{
public amount = 5;
....
}
3- Accessing the parent class inside the child class 3-访问子类中的父类
export class AppleComponent {
constructor( @Optional() public parent?: Parent) {
console.log('The amount in the parent is: 'this.parent?.amount)
}
...
}
The result from the console控制台的结果
The amount in the parent is: 5
That's it.而已。
Refrence: Find a parent by its class interface Refrence: 通过其类接口查找父级
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.