簡體   English   中英

NG2:我怎樣才能一般地訪問父組件?

[英]NG2: How can I access parent component generically?

在開始之前請注意,我最初是在 angular2 github 站點上作為功能請求提出這個問題的。 然而,該請求已關閉,我被建議將其張貼在這里。 在這里,我只是重復我最初的要求。 但是,您可以通過以下鏈接找到一些討論: https : //github.com/angular/angular/issues/10448

我需要能夠獲得對父組件的引用,而子組件不必知道父組件的類型。 基本上我需要這樣的東西(偽代碼):

    @Component({
        template: '<child></child>'
        directives: [Child]
    })
    class ParentComponent{}

    @Component({ selector: 'child' })
    class ChildComponent{
        constructor(@Parent() _parent: any){}
    }

基本上我需要ChildComponent_parent字段來引用ParentComponent 但是請注意_parent的類型是any 它是any因為它可以是任何,字面意思。 ChildComponent是一個通用組件,可以被任何類型的其他組件使用。 我知道有解決這個問題的方法,但它們都需要孩子知道父母的類型。 它是這樣的:

    @Component({ selector: 'child' })
    class ChildComponent{
        constructor(_parent: ParentComponent){}
    }

但同樣,這對我不起作用,因為ChildComponent可以用於任何類型的其他組件,並且沒有人知道另一個的類型。 所以我需要的是一些通用的方法將其父組件注入ChildComponent ,如組件樹中設置的那樣,而ChildComponent不知道父類型。 有誰知道我怎么能做到這一點?

您可以使用Injector API

對於 Angular2 最新版本和舊版本:

import { Injector } from '@angular/core';
import {AppComponent} from "./app.component";

@Component({ selector: 'child' })
class ChildComponent{
     constructor(private inj:Injector){
         let parentComponent = this.inj.get(AppComponent);
         console.log(parentComponent);
     }
}

使用@Input和一個小技巧將父對象的this發送給子對象。 我想你也可以@Output通過@Output從父級訪問子@Output

父組件

import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    template: '<app-child [parnt]="var2"></app-child>',
    style: ''
})
export class AppComponent {
    title = 'app works!';
    var1 = "val1";
    var2 = this;
}

子組件

import { Component, Input, EventEmitter, OnInit } from '@angular/core';

@Component({
  selector: 'app-child',
  template: '{{parnt.var1}}',
  style: ''
})
export class ChildComponent implements OnInit {
  @Input() parnt;
}

您應該會看到“val1”打印出來,即子模板中打印的父級 var1 的值。

感謝@yurzui 帶領我走向正確的方向......最后我找到了幾種不同的方法......不幸的是,所有方法都涉及訪問不太理想的私人成員......如果有人知道更好的方法,請說出來……謝謝

 constructor(private vcRef: ViewContainerRef){
    var parentComponent1 = this.vcRef.injector._view.context;
    console.log(parentComponent1);
    var parentComponent2 = this.vcRef._element.parentView.context;
    console.log(parentComponent2);
    console.log(parentComponent1 === parentComponent2);
  }

這是使其工作的方法。

@Component({
    selector: 'child'
})
class ChildComponent{
    constructor( @Optional() public myParent: ParentComponent ){}
}

您可以在Angular DI 文檔中找到更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM