从模板访问“ this”(组件实例)

时间:2018-11-27 00:17:14

标签: angular typescript angular-components

假设我们需要在模板中将一些子组件属性绑定到组件实例本身:

<child-component parent="???"></child-component1>

除了在父组件上声明专用属性之外,是否有其他方法可以实现:

public thisInstance: ParentComponent = this;

然后使用它:

<child-component parent="thisInstance"></child-component1>

更新1 :我正在寻找一种方法,该方法可以肯定为孩子提供父级,这意味着如果该孩子在不同层次结构上具有两个或多个相同组件类型的父级,我们就可以明确指定必须使用哪一个。

更新2 :我正在寻找一种不限制孩子的方法,可以使用确切的父类型。因此,我不确定是否可以使用某些基类(由父级实现)将父级注入子级的构造函数中作为令牌。

2 个答案:

答案 0 :(得分:0)

您可以尝试使用#selector绑定HTML,例如:

<child-component1 #parent [parent]="parent"></child-component1>

然后您可以在child-component1中将其父声明为@Input()。

答案 1 :(得分:0)

您可以像这样将子组件注入子组件构造器中

export class childComponent{
  constructor(private parent: ParentComponent){}
}

要适应这两个更新,可以创建一个服务可注入类,并在父组件oninit()中分配父组件实例,子组件中将使用同一实例。

@Injectable()
export class Service{
  private compInstance;
  setComponentInstance(_instance){
    this.compInstance = _instance;
  }
  getComponentInstance(_instance){
    this.compInstance = _instance;
  }
}

父组件

export class Parent{
    this.service.setComponentInstance(this);
}

子组件:

this.service.getComponentInstance();