2017-07-01 9 views
1

コンポーネント内にコンポーネントmyComponentがネストされていますが、アウトコンポーネントからネストされたコンポーネントの幅を取得するにはどうすればよいですか?角度 - ネストされたコンポーネントの取得htmlリファレンス

<div class="container">    
    <myComponent[compObj]="someObj"></myComponent> 
</div> 

ここ幅が必要です。

@Component({ 
}) 
export class OutterComponent { 
    // width = myComponentHtmlRef.width 
} 
+0

https://angular.io/guide/component-interaction –

答えて

0

あなたは幅を取得するために、子コンポーネントにゲッターを追加することができます。

export class MyComponent { 
    constructor(private el: ElementRef) { } 

    public get width(): number { 
    // Get the width however you like 
    return this.el.nativeElement.getBoundingClientRect().width; 
    } 
} 

その後、親にそのコンポーネントのゲッターにアクセス:

export class OuterComponent { 
    @ViewChild(MyComponent) child: MyComponent; 

    ngAfterViewInit() { 
    let width = this.child.width; 
    } 
} 
0

私は、要素の幅を式としてテンプレートに公開するNericディレクティブです。後で問題を再現するときにこれを再利用することができます。

@Directive({ 
    selector: 'on-width' 
}) 
export class OnWidthDirective implements DoCheck { 
    @Output('on-width') 
    public widths: EventEmitter<number> = new EventEmitter(); 

    private _lastWidth: number; 

    public constructor(private el: ElementRef) {} 

    public ngDoCheck(): void { 
     const w = this.el.nativeElement.getBoundingClientRect().width; 
     if(this._lastWidth !== w) { 
      this.widths.next(w); 
      this._lastWidth = w; 
     } 
    } 
} 

OutterComponentのテンプレートでは、どのテンプレート要素でも幅の変化を聴くことができます。

@Component({ 
    template: '<child-thing (on-width)="onWidth($event)"></child-thing>' 
}) 
export class OuterComponent { 
    public onWidth(width: number) { 
     console.log(width); // called when child resizes 
    } 
} 
+0

ニース実装:)私は似たようで始まったが、私は、各チェックの間に幅の計算があまりにも高価になるかもしれないと思ったので、方向を変えました。しかし、今は時期尚早に最適化していたと思います。 –

関連する問題