Angular 从指令访问外部组件实例
我有一个简单的组件,只有一个输入[id],还有一个使用“我的指令”的模板Angular 从指令访问外部组件实例,angular,angular-directive,angular-components,Angular,Angular Directive,Angular Components,我有一个简单的组件,只有一个输入[id],还有一个使用“我的指令”的模板 <div> <div my-directive> hello world </div> </div> 你好,世界 简单组件将在模板中多次使用: <simple-component [id]="1"></simple-component> <simple-component [id]="2"></s
<div>
<div my-directive>
hello world
</div>
</div>
你好,世界
简单组件将在模板中多次使用:
<simple-component [id]="1"></simple-component>
<simple-component [id]="2"></simple-component>
我是否可以从每个我的指令实例中访问简单组件的实例?
目标是每个my指令实例都知道其简单组件“主机/外部”实例,
例如,为了访问它们的“id”属性。是的,有一种方法可以使用
@Host()
分辨率修饰符访问父组件(有关的详细信息)。基本思想是通过使用依赖项注入来导航组件树,以便从子元素中找到对父元素的引用。这里有几个很好的例子
默认情况下,Angular向上搜索提供的实例,一直搜索到NullInjector
(层次结构中最高的)。如果它没有找到实例,就会抛出异常,除非我们使用@Optional
,在这种情况下,它返回null
。
在您的特定示例中,我们使用Host()
告诉Angular停止搜索,并将此组件作为搜索时的最后一站。我们不必使用它,即使省略了Host()
,它仍然可以工作
在my directive.directive.ts
文件中:
构造函数(@Host()私有父级:SimpleComponent){
//这里我们有一个SimpleComponent的实例,我们可以访问它的属性,除了输入属性,这些属性仍然没有在构造函数中设置
}
我创建了一个简单的示例来演示这一点
EDIT:在这里我们可以找到指令中的AppComponent
的实例,它是SimpleComponent
的父级。这里我们不能使用Host()
,因为搜索将以指令作为最后一个停止点停止(并且AppComponent
在链中处于较高的位置)。所以我们只是不添加任何内容,就得到了正确的引用
希望这能有所帮助。您可以通过使用服务来实现:
@Injectable()
export class IdsTrackerService {
private ids$$: BehaviorSubject<{ [key: string]: true }> = new BehaviorSubject(
{}
);
public ids$: Observable<string[]> = this.ids$$
.asObservable()
.pipe(map(ids => Object.keys(ids)));
public addId(id: string): void {
if (!this.ids$$.value[id]) {
this.ids$$.next({
...this.ids$$.value,
[id]: true
});
}
}
}
不要忘记在组件级而不是模块级或全局级提供服务:
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
// declare the provider on a component basis
// so you get a different instance of the service per component
providers: [IdsTrackerService]
})
这是一个带有调试视图的实时演示,用于显示已注册的ID:检查我的示例:
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
// declare the provider on a component basis
// so you get a different instance of the service per component
providers: [IdsTrackerService]
})