我有一个嵌套在组件中的组件myComponent
,如何从outter组件中获取嵌套组件的宽度?
<div class="container">
<myComponent[compObj]="someObj"></myComponent>
</div>
这里需要宽度:
@Component({
})
export class OutterComponent {
// width = myComponentHtmlRef.width
}
答案 0 :(得分:0)
您可以在子组件中添加一个getter来获取宽度:
export class MyComponent {
constructor(private el: ElementRef) { }
public get width(): number {
// Get the width however you like
return this.el.nativeElement.getBoundingClientRect().width;
}
}
然后访问父组件中该组件的getter:
export class OuterComponent {
@ViewChild(MyComponent) child: MyComponent;
ngAfterViewInit() {
let width = this.child.width;
}
}
答案 1 :(得分:0)
我会创建一个泛型指令,将元素宽度作为表达式暴露给模板。您可以稍后再次使用它,因为您将再次遇到此问题。
@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
}
}